Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

condition || raise("error")

Tags:

ruby

I'm just wondering where this syntax documented:

1 > 2 || raise("error")

I have tried use it as condition:

1 > 2 || p "test"

but it doesn't work:

SyntaxError: (irb):9: syntax error, unexpected tSTRING_BEG, expecting keyword_do or '{' or '('
1 > 2 || p "test"
            ^
        from C:/Ruby193/bin/irb:12:in `<main>'
like image 502
ceth Avatar asked Nov 30 '22 06:11

ceth


2 Answers

What you have doesn't work because you need parenthesis:

1 > 2 || p("test")

Note that or (and and) has a different precedence than &&/|| and thus will work without parenthesis (and with what you're doing makes more semantic sense):

1 > 2 or p "test"

as will unless:

p "test" unless 1 > 2
like image 88
Andrew Marshall Avatar answered Dec 15 '22 12:12

Andrew Marshall


It's just an inline way to say "raise an error if the condition is false". The || is just a common OR operator, and the expression is evaluated using short-circuit evaluation. Nevertheless, for clarity purposes, I would prefer this:

raise("error") unless 1 > 2
like image 40
alf Avatar answered Dec 15 '22 13:12

alf