Variables initialization, assignments and swapping in ruby

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

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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.