[ruby-core:66067] [ruby-trunk - Bug #10450] multiple assignment in conditional

From: jballanc@...
Date: 2014-11-03 10:11:02 UTC
List: ruby-core #66067
Issue #10450 has been updated by Joshua Ballanco.


Yes, but consider:

~~~
if a = (b, c = false, false)
  puts "a is #{a}, b is #{b}, c is #{c} and everything together is true"
end
~~~

So if you were hoping to use multiple assignment to check the `&&`-ed boolean values of the individual conditions (or even the `||`-ed value), then you would be rudely surprised. In fact:

~~~
def gimmie_nil
  nil
end

if a = (b, c = gimmie_nil(), gimmie_nil())
  puts "Still true..."
end
~~~
...there is no way that the conditional would ever evaluate to false!

----------------------------------------
Bug #10450: multiple assignment in conditional
https://bugs.ruby-lang.org/issues/10450#change-49785

* Author: bug hit
* Status: Open
* Priority: Normal
* Assignee: 
* Category: 
* Target version: 
* ruby -v: ruby 2.1.4p265 (2014-10-27 revision 48166) [x86_64-linux]
* Backport: 2.0.0: UNKNOWN, 2.1: UNKNOWN
----------------------------------------
multiple assignment is an expression whose value can be truthy (array) or falsy (nil, false), so why is there a restriction on its use in conditionals?  A warning perhaps is justified, but a syntax error, why?


irb(main):001:0> if a, b = nil then 1 else 0 end
SyntaxError: (irb):1: syntax error, unexpected ',', expecting keyword_then or ';' or '\n'
if a, b = nil then 1 else 0 end
     ^
(irb):1: syntax error, unexpected keyword_then, expecting end-of-input
if a, b = nil then 1 else 0 end
                  ^
	from /home/alex/.rbenv/versions/2.1.4/bin/irb:11:in `<main>'
irb(main):002:0> if (a, b = nil) then 1 else 0 end
SyntaxError: (irb):2: multiple assignment in conditional
	from /home/alex/.rbenv/versions/2.1.4/bin/irb:11:in `<main>'
irb(main):003:0> (a, b = nil) ? 1 : 0
SyntaxError: (irb):3: multiple assignment in conditional
	from /home/alex/.rbenv/versions/2.1.4/bin/irb:11:in `<main>'
irb(main):004:0> (a, b = nil)
=> nil




-- 
https://bugs.ruby-lang.org/

In This Thread

Prev Next