1
array = []
array << true ? "O" : "X"

i did expect to ["O"].
but array is [true]

and now i use push

array.push(true ? "O" : "X")

then result is ["O"]

actually true ? "O" : "X" return to "O"
my assumption was ["O"] if use << and push both. but it's not.
anybody known why?

hiphapis
  • 151
  • 1
  • 9
  • 6
    It's about precedence. As you see, `<<` has higher precedence than ternary operator. `array << (true ? '0' : 'X')` will work as you expect. – Marek Lipka Apr 08 '15 at 07:07
  • `<<` is just a method. you can call it like that `array.<<(true ? "O" : "X")`. difference between push is only that push can accept multiple arguments `push *args`, but `<<` only 1 – beornborn Apr 08 '15 at 09:28

1 Answers1

1

You can visualize the how the Ruby parser is seeing your 2 expressions using ruby_parser gem.

require 'ruby_parser'
require 'pp'

pp RubyParser.new.parse 'true ? "O" : "X"'
# => s(:if, s(:true), s(:str, "O"), s(:str, "X"))

Now, based on the above parsing result, compare this :

pp RubyParser.new.parse '[] << true ? "O" : "X"'
# => s(:if, s(:call, s(:array), :<<, s(:true)), s(:str, "O"), s(:str, "X"))
#                    <-----------------------> look this part

And then,

pp RubyParser.new.parse '[].push(true ? "O" : "X")'
# => s(:call, s(:array), :push, s(:if, s(:true), s(:str, "O"), s(:str, "X")))
Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317