Why doesn't this work if the test works?

I have a built-in if it does not do what I thought, and I did it in a console example for clarity.

I thought that inline if was syntactically the same as multi-line if, but it seems like it is not.

foo = "chunky" (bar1 = foo) if (!defined?(bar1) && foo) bar1 

In this case, bar1 ends with nil. If I restructure it on

 foo = "chunky" if !defined?(bar2) && foo bar2 = foo end bar2 

then it works - bar2 is set to "chunky" (I used bar2 instead of bar1 in the second example to make sure I used the undefined variable in each case).

Is this the case when inline, if it always sets bar1 to something, defaults to nil? I thought that he simply did not evaluate the part before if, if the test returns false.

+4
source share
1 answer

This fails because, as soon as a single word is displayed on the left side of the assignment, it is initialized to nil . So when you execute (bar1 = foo) if (!defined?(bar1) && foo) , bar1 will be nil in the defined? Tag . Here's a simplified example:

 >> defined? foo => nil >> foo = 1 if false => nil >> foo => nil >> defined? foo => "local-variable" 
+7
source

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


All Articles