Given:
ary =3D Array.new
some_hash =3D {'a' =3D> 1, 'b' =3D> 2, 'c' =3D> 3}
another_array =3D ['a', 'c']
Then:
another_array.each do |x|
=A0 ary << =A0some_hash.has_key?(key) ? ' ' : some_hash[key]
end
Expected:
ary should be [1, ' ', 3]
Actual:
[true, false, true]
Question:
Why does that happen?
First of all, I assume you copy/pasted wrong, since I get
NameError: undefined local variable or method `key' for main:Object
Assuming you want to query the hash for each value of the
another_array, you can do this:
irb(main):025:0> another_array.each do |x|
irb(main):026:1* ary << (some_hash.has_key?(x) ? ' ' : some_hash[x])
irb(main):027:1> end
=3D> ["a", "c"]
irb(main):028:0> ary
=3D> [" ", " "]
Please note the parenthesis.
And I have the suspicion that you have the logic backwards, since you
return " " when the hash has the key, and go to the hash when it
doesn't (which will always return nil or the default value). Maybe you
wanted this:
irb(main):033:0> ary =3D []
=3D> []
irb(main):034:0> another_array.each do |x|
irb(main):035:1* ary << (some_hash.has_key?(x) ? some_hash[x]: ' ')
irb(main):036:1> end
=3D> ["a", "c"]
irb(main):037:0> ary
=3D> [1, 3]
Another way of doing this, more idiomatic would be:
irb(main):038:0> ary =3D another_array.map {|x| some_hash.has_key?(x) ?
some_hash[x]: ' '}
=3D> [1, 3]
irb(main):039:0> ary
=3D> [1, 3]
But anyway, you won't get a three element array, since you are
iterating over another_array, which has only two entries. Can you
explain how you should obtain 3 elements in the array? Is it all
elements in the hash that have their key in the another_array? If so:
irb(main):040:0> ary =3D some_hash.map {|k,v| another_array.include?(k) ? v=
: ' '}
=3D> [1, " ", 3]
Hope this helps,
Jesus.