Susan Potter

idioms

snippets

Ruby Idioms, Part 7

This idiom I have seen a little more in Rails than I have seen in Ruby, but I am putting it in this Ruby Idioms series anyway. First off, most of you will know by know that you can "transparently" provide a method in Ruby a Hash. What do I mean by "transparently"? Well have a look at the code example below: user = User.find(:first, :include …

snippets

Ruby Idioms, Part 6

Tonight I remembered couple more idioms in Ruby and felt compelled to share. In Javafied Ruby code (below) we often see something like the following: if something for role in user.roles return true if @@roles.include? role end end Now when I first started writing Ruby code almost 3 years ago, I thought looping through a collection like above was the …

snippets

Ruby Idioms, Part 5

Some of you may say this isn't strictly an idiom, but it is dependent on Ruby's core API and classes, so I have included it. Ranges are a very nice low-level abstraction and can save Ruby developers a lot of time for certain coding needs. In a previous idiom example on this blog I had a list of positive odd numbers under 7. Well typing this out by …

snippets

Ruby Idioms, Part 4

To splat or not to splat, that is the question. In Java to unpack an array's values into separate variables you would need to do something like the following: burgers = [:hamburger, :bocaburger, :gardenburger, :turkeyburger] t = burgers[0] u = burgers[1] v = burgers[2] w = burgers[3] In the Ruby mindset this would look more like the following: burgers …

snippets

Ruby Idioms, Part 3

Now, probably the biggest difference after the syntax, and the non-static nature of Ruby for Java heads to get used to is that Ruby is an "expressionist" language. Meaning almost all statements in Ruby evaluates to a value, i.e. everything that reasonably can be is an expression in Ruby is. This is definitely not the way Java thinks or works. So this …

snippets

Ruby Idioms, Part 2

Now the "idiom" we will use is not specific to Ruby, since I am pretty sure Perl has one of the constructs we will use to solve the stated problem, but it is still idiomatic, since the majority of popular OO languages (static, dynamic or otherwise) do not have it (as far as I know). Also some consider this to be a sub-optimal idiom, because there is …

snippets

Ruby Idioms, Part 1

With more people moving to Ruby everyday from languages like Java, I wanted to create blog entries on the most common Ruby idioms (especially ones frequently found in Rails core or Rails application code) and briefly explain how to convert your Java mindset to Ruby (over time). This is the first installment. First let us inspect what we might do in Java …