Why is there a return or b error in Ruby?

This is normal:

def foo a or b end 

It's also good:

 def foo return a || b end 

This returns a void value expression :

 def foo return a or b end 

Why? It is not even executed; it does not perform syntax checking. What does void value expression mean?

+7
source share
3 answers

return a or b interpreted as (return a) or b , so the value of return a necessary to calculate the value (return a) or b , but since return never leaves the value in place (since it leaves this position), it is not intended to returning the actual value to its original position. And therefore, the whole expression stays with (some_void_value) or b and gets stuck. This is what it means.

+8
source

Just because or has a lower priority than || , which means that return a will execute before or b , or b therefore unavailable

+2
source

From a similar question I asked earlier, Stefan explained in a comment that or and and are actually control flow operators and should not be used as Boolean operators ( || and && respectively).

He also referred to an article explaining the reasons for these control flow statements :

and and or arise (like so many of Ruby) in Perl. In Perl, they were mainly used to change the control flow, similar to the if and unless . (...)

They give the following examples:

and

 foo = 42 && foo / 2 

This will be equivalent to:

 foo = (42 && foo) / 2 # => NoMethodError: undefined method `/' for nil:NilClass 

The goal is to assign the number foo and reassign it with half its value. Thus, the and operator is useful here because of its low priority, it changes / controls , which will be a normal stream of individual expressions:

 foo = 42 and foo / 2 # => 21 

It can also be used as the inverse of an if in a loop:

 next if widget = widgets.pop 

Which is equivalent:

 widget = widgets.pop and next 

or

useful for combining expressions together

If the first expression fails, execute the second, etc:

 foo = get_foo() or raise "Could not find foo!" 

It can also be used as:

Modified unless modifier:

 raise "Not ready!" unless ready_to_rock? 

Which is equivalent:

 ready_to_rock? or raise "Not ready!" 

Therefore, since sawa explained the expression a or b in:

 return a or b 

has a lower priority than return a , which, when executed, skips the current context and does not provide any value (void value). Then it causes an error ( repl.it execution ):

(repl): 1: void value expression

 puts return a or b ^~ 

This answer was made possible thanks to Stefan's comments (thanks).

+1
source

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


All Articles