Ruby doesn't "bother me" like Prolog?

So I'm new to Prolog and Ruby. Studying Prolog at University and Ruby on my own. And I thought, if in Ruby there is a variable "not caring" or "discard", as it is in Prolog.

I just opened irb and just did it (suppose the underscore was a “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 I actually expected. But then I was curious where, where is the meaning of the underline and what class was it

 1.9.2-p290 :006 > _ => 3 1.9.2-p290 :008 > _.class => Fixnum 

Well, that is weird. Shouldn't this drop value? Why is a different value stored?

Then, doing more underscore tests, I saw what really happened, 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 exactly should I emphasize? Is it really not important, a variable or something else? What is the real name for him? (because I don’t find many things with a “ruby variable not important” with google)

+4
source share
3 answers

What throws you away is that you see two different underscores.

  • In the argument lists, it acts as a “non-caring variable,” as in Prolog.

  • Outside of argument lists, this is just a regular identifier. In the IRB, it is related to the previous result. Since your last entry was c = 3 , _ is equal to 3. This is only in IRB, however - this does not happen in regular Ruby programs.

+10
source
  • In the Ruby community, _ means "don't care."
  • Ruby _ doesn't mean anything; it's an identifier, like any other.
  • In the YARV Ruby interpreter, the warning "unused local variable" is suppressed for _ , thereby encoding the convention in # 1.
  • In IRb, _ bound to the value of the last expression.
+9
source

An underscore in Ruby acts like any normal variable, except that it is a bit more special. It really means "I don't care."

As an example, suppose you iterate over an array whose elements are 3-element arrays:

 array = [[1,2,3],[4,5,6],[7,8,9],...] 

Say you are only interested in the average value. With _ you can do this:

 array.each do |_, number, _| # do something end 

If you try to do this with another variable, you will get the (expected) error that you duplicate the variable:

 array.each do |v, number, v| # do something end => SyntaxError: (eval):2: duplicated argument name 
+5
source

Source: https://habr.com/ru/post/1410891/


All Articles