Thursday, November 5, 2009

Variables initialization, assignments and swapping in ruby

by Sandip Ransing 0 comments
Tags

Just a single line variable swap in ruby

x,y=y,x
Example:

irb>> x = "Fun"
=> "Fun"
irb>> y = "Rails"
=> "Rails"
irb>> x,y = y,x
=> ["Rails", "Fun"]
irb>> p x
"Rails"
=> nil
>> p y
"Fun"
Variable assignments in Ruby
we can do multiple assignments in a single line.

irb>> a,b,c,d = 1,2,3,4
=> [1, 2, 3, 4]


here is interpretation of above line

irb>> p "a => #{a} b => #{b} c => #{c} d => #{d}"
"a => 1 b => 2 c => 3 d => 4"

Multiple assignments in ruby


a = b = c = d = 12

This means a,b,c,d variables has value 12

blog comments powered by Disqus

About The Author

Sandip is a ruby on rails developer based in pune and also a blogger at funonrails. Opensource contributor and working with Josh software Private Limited. for more info read Follow Sandip on Twitter for updates.

Connect With Me...

Github Projects

@sandipransing Twitter