Written on 7:32:00 PM by S. Potter
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 will take some adjusting to. Don't worry I will show you an example. Now the Javafied Ruby code we will optimize is shown below:
user_id = nil if comments if comments.first if comments.first.user user_id = comments.first.user.id end end endNow that is some ugly code, but sometimes doing something equivalent to that in Java is very necessary. So how would a true Rubyist write that code:
user_id = comments && comments.first && comments.first.user && comments.first.user.idNow let us walk through what this really does.
commentsis evaluated, if it is
nil, then the value
nilis returned, the boolean expression is exited out of (because it is all &&'s and fails at the first condition, thus the whole boolean expression fails) and
nil, which was the last value evaluated in that expression is set to
user_id. This is the same outcome that would have occurred in the first code snippet.
- We repeat the process of the previous step for
nilis encountered and set as the value of user_id or the final part of the boolean expression evaluates to a non-nil value and that value is set to the value of user_id.