So I'm both new to Prolog and Ruby. Learning Prolog at university and Ruby at my own. And I was thinking if there is a "don't care" or "trow away" variable in Ruby as there is in Prolog.
I just opened irb and just did this (supposing underscore was the "don't care" sign)
1.9.2-p290 :003 > _, b, c = [1,2,3]
=> [1, 2, 3]
1.9.2-p290 :004 > b
=> 2
1.9.2-p290 :005 > c
=> 3
The results are actually what I expected. But then I was curious about what where the value of underscore and what class it was
1.9.2-p290 :006 > _
=> 3
1.9.2-p290 :008 > _.class
=> Fixnum
Well, that's odd. Shouldn't it trow the value away? Why other value being stored?
Then doing more tests with underscore I saw what actually it was happening, it has the last evaluated value.
1.9.2-p290 :017 > 1
=> 1
1.9.2-p290 :018 > _
=> 1
1.9.2-p290 :019 > "string"
=> "string"
1.9.2-p290 :020 > _
=> "string"
1.9.2-p290 :021 > Hash
=> Hash
1.9.2-p290 :022 > _
=> Hash
So my question is: What's actually underscore for? Is it really a don't care variable or something else? What's the real name for it? (because I don't find many thing with "don't care ruby variable" with google)
What's throwing you is that you're seeing two different uses of the underscore.
In argument lists, it acts like a "don't care variable," like in Prolog.
Outside of argument lists, it's just a normal identifier. In IRB, it's bound to the previous result. Since your last input was c = 3
, _ is 3. This is only in IRB, though — it doesn't happen in normal Ruby programs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With