Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the logic behind this result?

Tags:

ruby

def foo(_, _='override')
  _
end

p foo("bye bye")
p foo("hello", "world")

Output:

"override"
"hello"

I could understand if the result was:

"override"
"world"

or even:

"bye bye"
"hello"

But the result I'm getting causes me confusion.

like image 905
Gerry Avatar asked Mar 24 '16 15:03

Gerry


People also ask

How do you identify a logic statement?

Anything that lets us infer a new fact about something mathematical from given information is a logical statement. For example, “The diagonals of a rectangle have the same length” is a logical statement. The hypothesis is the part that can help us if we know it's true.

What is proposition in logic examples?

Definition: A proposition is a statement that can be either true or false; it must be one or the other, and it cannot be both. EXAMPLES. The following are propositions: – the reactor is on; – the wing-flaps are up; – John Major is prime minister.

What does if mean in logic?

‍ IF AND ONLY IF, is a biconditional statement, meaning that either both statements are true or both are false. So it is essentially and “IF” statement that works both ways. ‍


2 Answers

Default arguments are evaluated earlier in time than regular arguments if an argument is passed for it, otherwise they are evaluated last. Almost certain but unsure how to prove it.

Meaning in this example:

at time 0 call p foo("hello", "world")

at time 1 _ = 'override'

at time 2 _ = "world"

at time 3 _ = "hello"

at time 4 variables are printed and you see "hello"

EDIT here is some evidence:

def foo(_, _='override',_)
  _
end

p foo("bye bye","goodbye")
p foo("hello", "world", "three")

prints

"override"
"three"
like image 153
Mike S Avatar answered Oct 20 '22 07:10

Mike S


Ican't find better explanation than this one

ruby magic underscore

The reason for this is found in Ruby’s parser, in shadowing_lvar_gen. All the normal checks for duplication are skipped iff the variable name consists of exactly one underscore.

like image 37
Abdoo Dev Avatar answered Oct 20 '22 08:10

Abdoo Dev