Ruby Quicktips Logo

Ruby Quicktips

Random Ruby and Rails tips.
This blog is dedicated to deliver short, interesting and practical tidbits of the Ruby language and Ruby on Rails framework. Read more...

Your submissions are more than welcome!
Feb 8 ’10

Multiple Assignment

You can assign multiple values to multiple variables like this:

foo, bar = [1, 2]  # foo = 1; bar = 2
foo, bar = 1, 2    # foo = 1; bar = 2
foo, bar = 1       # foo = 1; bar = nil

F.e. this can be useful for splitting names:

>> name = "Joe Bloggs"
=> "Joe Bloggs"
>> firstname, lastname = name.split
=> ["Joe", "Bloggs"]
>> firstname
=> "Joe"
>> lastname
=> "Bloggs"
>> name
=> "Joe Bloggs"

Read more on assignment in Ruby.

24 notes 0 comments

Comments

You can use HTML tags for formatting. Wrap code in <code> tags and multiple lines of code in <pre><code> tags.

blog comments powered by Disqus