Ruby 101 for .NET developers: Multiple assignments made easy 8
Here’s another ruby-ism that wasn’t obvious to me at first. In C#, I might have a class that took several parameters in the constructor, and I would need to save those values in some private member variables. My code always looked something like this:
// C# code
class Team
{
private Schedule schedule; // reference to a Schedule object
private string name;
private string city;
public Team(string name, string city, Schedule schedule)
{
this.name = name;
this.city = city;
this.schedule = schedule;
}
}
I’ve done this thousands of times, and it seemed easy enough to me that I never thought about how it could ever be any better. But actually I was just a mouse who’d been trained to run through a maze if I wanted some cheese. Look at the Ruby equivalent:
class Team
def initialize(name, city, schedule)
@name, @city, @schedule = name, city, schedule
end
end
Here I’ve taken advantage of Ruby’s multiple assignment feature to quickly initialize everything.
Also, behold the following… let’s say the name, city, and schedule should be read-only properties of my class. Let’s run through another maze:
// C# code
class Team
{
private Schedule schedule; // reference to a Schedule object
private string name;
private string city;
public Team(string name, string city, Schedule schedule)
{
this.name = name;
this.city = city;
this.schedule = schedule;
}
public string Name
{
get { return name; }
}
public string City
{
get { return city; }
}
public Schedule Schedule
{
get { return schedule; }
}
}
And the ruby equivalent:
class Team
attr_reader :name, :city, :schedule
def initialize(name, city, schedule)
@name, @city, @schedule = name, city, schedule
end
end
Sure feels good to get out of that rat race.



Great post Jeff; as someone still more familiar with C# than Ruby I appreciate the comparison....and the elegance of Ruby. :)
Nice explanation of multiple assignment Jeff.
It's almost painful, when you actually use both languages everyday :)
Thank you for these postings, keep them coming. The comparisons are quite helpful.
I actually prefer the one line per assignment in this case. I find having to match up the assignments when they're all in one line to be a bit difficult, especially when you have more than the three shown here.
In ruby you get rid of the curlies and the this keyword. That in addition to tabbing your equals signs for alignment gives you a very readable block.
Having written about fifty getters and setters in C# at work today, I'm happy to be home now with attr_accessor!
alaxy7908@softiesonrails.com
The never-ending regress in the series of empirical conditions, so far as regards the transcendental aesthetic, constitutes the whole content for the Ideal, and the phenomena have nothing to do with the empirical objects in space and time.
However, it remains a mystery why the empirical objects in space and time are what first give rise to, certainly, the noumena.