Justin Collins
10/3/2008 9:02:00 AM
list. rb wrote:
> Awesome!
> For the record, this is the code mentioned in the blog:
>
> 1 if (comments = @attributes['comments']) &&
> comments.is_a?(String) 2 @attributes['comments'] =
> comments.split(" ") 3 end
>
>
> I never knew it was possible to define a variable from within a condition.
> Goes to show you that ruby offers plenty of rope to hang yourself if you are
> not careful. Correction -I have accidentally done it in the past and never
> viewed it as a feature until now.
>
> <snip>
It's not really a feature of Ruby, it is common in many languages and is
also a common source of bugs and logical errors.
For example, in C/C++, assignment is always true, so in cases when you
intend to do comparison but miss the second equals sign, you end up
doing assignment. Not only is it subtle logically, it is also subtle
visually since assignment and comparison look so similar (in these
languages).
The issue is so common that if Ruby thinks you are intending to do
comparison, you will typical getting a warning: "warning: found = in
conditional, should be =="
My thoughts on the code itself is that I would not have done it that way
at all. Why even introduce a new variable unless, somehow, performance
was an issue? The overall style is not particularly 'Rubyesque" in my
opinion. I would have probably written it as:
@attributes['comments] = @attributes['comments'].split if
@attributes['comments'].is_a? String
> However neither of these two yield true in a conditional:
> puts "you wont see this" unless (a = nil) or (!a = a)
>
(!a = a) [ actually, !(a = a) ] is true, so the "puts" statement is not
executed. Maybe you meant 'if' instead of 'unless'?
-Justin