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 ?
2 comments
Posted in Ruby
Written on Sun, 18 May 2008 at 10:40 pm
Tags: Ruby
If you liked this post, then consider subscribing to our full RSS feed.
May 19th, 2008 at 4:55 am
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”
May 19th, 2008 at 7:17 am
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.