Variables initialization, assignments and swapping in ruby

Just a single line variable swap in ruby



irb>> x = “Fun”

=> “Fun”

irb>> y = “Rails”

=> “Rails”

irb>> x,y = y,x

=> [“Rails”, “Fun”]

irb>> p x


=> nil

>> p y


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

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.