One more behaviour of ruby

By Rimpy

Today while working with ruby i noticed one more surprising behaviour of ruby.

1
2
arg1="Ruby", arg2="On", arg3="Rails" 
puts "#{arg1},#{arg2},#{arg3}"

What should be the results?
Well i was expecting to be printed like “Ruby”,”On”,”Rails” but the result was “RubyonRails”, “On”, “Rails”
To understand this behaviour i did some more experiments in “irb”

1
2
3
puts arg1.class.to_s    # result  Array 
puts arg2.class.to_s    # result String 
puts arg3.class.to_s    # result String

Now the question is, Why arg1 is interpreted as an array? and why not the arg2 ?

Share/Save

2 Responses to “One more behaviour of ruby”

  1. Vidar Hokstad Says:

    What happens is that the line is parsed like this:

    arg1=”Ruby”, (arg2=”On”), (arg3=”Rails”)

    A comma separated list on the right hand side will turn into an array. A common idiom for it is when you have multiple initializations you want to make:

    a,b,c = d,e,f

    In this case, the parser sees the comma, decides this is an array, and then goes on to parse the rest in light of that.

    arg2 and arg3 then gets initialized, and the result of an assignment expression is the value being assigned, so those end up in the array too. Arg2 doesn’t end up in the array because it is being treated by the parser as an array element, so “,” terminates the expression and starts the next - there’s nothing there to introduce a new array scope.

    You can either separate them with semicolon instead, or you can do:

    arg1, arg2, arg3 = “Ruby”, “On”, “Rails”

  2. Rimpy Says:

    Hi Vidar,
    Thanks for your explanation. But what exactly the use of this particular arg1=”Ruby”,arg2=”On”,arg3=”Rails” expression. well here i may need to be corrected. but i think this expression has no real use.

Leave a Reply