From: "David A. Black" Date: 2008-10-03T18:49:27+09:00 Subject: Re: Is Assignment in a Conditional an Idiom? Hi -- On Fri, 3 Oct 2008, worthee@gmail.com wrote: > Hi > > I was just reading the following blog post > http://www.elctech.com/blog/clarity-over-cleverness-but-what-is-clever, > and like the author, it is the first time I have seen code as he > describes. From the comments it would seem that some think it is an > idiom to be used, and perhaps others do not. > > Just curious as to how common this use it? I do tend to side with > view that it is not clear at first glance. It depends whose first glance, I guess. It was clear to me, and I think it's something that's common enough that every Rubyist should be ready and willing to understand it. For better or worse, clarity and cleverness are fuzzy concepts, but in this case it's a pretty common idiom and not a wildly inventive or convoluted elaboration of the language. We all go through the process of not quite getting something, and then having the "Ah ha!" moment. I don't think the fact that the blogger you quote had that experience means that this is something to avoid. It's not my favorite idiom, though; it always has a slightly unbalanced, side-effect-esque feel to it. But it's liveable with. Ruby does something rather cool, though, to help you with this idiom: if you do accidentally leave off the second = in a case where the rhs can be statically determined to be true, you get a warning: >> if x = 10; end (irb):3: warning: found = in conditional, should be == There's no reason you would ever say "if x = 10", since it will be true 100% of the time. If the rhs is not unchangeably true, you don't get the warning: >> y = 10 => 10 >> if x = y; end => nil David -- Rails training from David A. Black and Ruby Power and Light: Intro to Ruby on Rails January 12-15 Fort Lauderdale, FL Advancing with Rails January 19-22 Fort Lauderdale, FL * * Co-taught with Patrick Ewing! See http://www.rubypal.com for details and updates!