Bug #4914
closedArray#index fails when used in if statement assignment
Description
cat /etc/issue: Ubuntu 11.04
rvm -v: rvm 1.6.2
rvm 1.9.2, ruby -v: ruby 1.9.2p180 (2011-02-18 revision 30909) [x86_64-linux]
Also tested with: rvm 1.9.2-head, ruby -v: ruby 1.9.2p274 (2011-06-06 revision 31932) [x86_64-linux]
Test code:
a = [:a, :b, :c]
for k in 'a'..'c'
if i = a.index(k.to_sym) && k.to_s =~ /b/
puts i
end
end
for k in 'a'..'c'
i = a.index(k.to_sym)
if i && k.to_s =~ /b/
puts i
end
end
output:
0
1
expected output:
1
1
Updated by mfn (Markus Fischer) over 13 years ago
It "works" for me if you change the &&
to and
; so I think it's a precedence issue you're facing here.
I think this blog post here has some good examples which I think directly apply to your case: http://blog.jayfields.com/2007/08/ruby-operator-precedence-of-and-which.html
Updated by matz (Yukihiro Matsumoto) over 13 years ago
- Status changed from Open to Rejected
not a bug. run the following:
a = [:a, :b, :c]
for k in 'a'..'c'
if i = a.index(k.to_sym) && k.to_s =~ /b/
puts i
end
end
for k in 'a'..'c'
if i = (a.index(k.to_sym) && k.to_s =~ /b/)
puts i
end
end
for k in 'a'..'c'
if (i = a.index(k.to_sym)) && k.to_s =~ /b/
puts i
end
end
for k in 'a'..'c'
i = a.index(k.to_sym)
if i && k.to_s =~ /b/
puts i
end
end
Updated by judofyr (Magnus Holm) over 13 years ago
Ruby parses your code like this:
if i = (a.index(k.to_sym) && k.to_s =~ /b/)
You can fix this by using "and" or explicit parenthesis:
if i = a.index(k.to_sym) and k.to_s =~ /b/
if (i = a.index(k.to_sym)) && k.to_s =~ /b/
// Magnus Holm
On Tue, Jun 21, 2011 at 22:28, Benjamin ter Kuile bterkuile@gmail.com wrote:
Issue #4914 has been reported by Benjamin ter Kuile.
Bug #4914: Array#index fails when used in if statement assignment
http://redmine.ruby-lang.org/issues/4914Author: Benjamin ter Kuile
Status: Open
Priority: Normal
Assignee:
Category:
Target version:
ruby -v: 1.9.2p180 (2011-02-18 revision 30909) [x86_64-linux]cat /etc/issue: Ubuntu 11.04
rvm -v: rvm 1.6.2
rvm 1.9.2, ruby -v: ruby 1.9.2p180 (2011-02-18 revision 30909) [x86_64-linux]
Also tested with: rvm 1.9.2-head, ruby -v: ruby 1.9.2p274 (2011-06-06 revision 31932) [x86_64-linux]Test code:
a = [:a, :b, :c]
for k in 'a'..'c'
if i = a.index(k.to_sym) && k.to_s =~ /b/
puts i
end
end
for k in 'a'..'c'
i = a.index(k.to_sym)
if i && k.to_s =~ /b/
puts i
end
endoutput:
0
1expected output:
1
1