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

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
  • 113,563
  • 27
  • 250
  • 306