From: "Matthew K. Williams" Date: 2009-11-20T03:46:27+09:00 Subject: Re: Ternary Operator and Arrays On Fri, 20 Nov 2009, Felix Dominguez wrote: > Given: > ary = Array.new > some_hash = {'a' => 1, 'b' => 2, 'c' => 3} > another_array = ['a', 'c'] > > Then: > another_array.each do |x| > ary << some_hash.has_key?(key) ? ' ' : some_hash[key] > end > > Expected: > ary should be [1, ' ', 3] > > Actual: > [true, false, true] > > Question: > Why does that happen? > You need parenthesis around the ternary operation. The reason being is that << has a higher precedence than ?:, so it evaluates just the some_hash.has_key?(key), giving a true or a false value. In general, while parenthesis are often optional in Ruby, if you're not sure how something works (or it's not clear), parenthesis are your friend. Matt