Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby "don't care variable" same as Prolog's? [duplicate]

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)

like image 438
Ismael Avatar asked Nov 28 '22 09:11

Ismael


1 Answers

What's throwing you is that you're seeing two different uses of the underscore.

  1. In argument lists, it acts like a "don't care variable," like in Prolog.

  2. 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.

like image 56
Chuck Avatar answered Nov 30 '22 22:11

Chuck