From: "list. rb" Date: 2008-10-03T15:22:14+09:00 Subject: Re: Is Assignment in a Conditional an Idiom? ------=_Part_14499_25493366.1223015011656 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit Content-Disposition: inline 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. One thing I found intriguing, was how the conditions were looking at the response from the definition, not the value of the variable being defined. That makes sense in thinking about it but For example, in IRB the second line yields false: irb(main):001:0> (a = nil) => nil irb(main):002:0> (!a = a) => true However neither of these two yield true in a conditional: puts "you wont see this" unless (a = nil) or (!a = a) I found the logistics(or lack thereof) of the example annoying. Rob is spot on in saying being that an object of type String can never be nil. The only excuse one could have for using this code is if they referenced the comments variable outside of the if statement somewhere else. At which point the comments variable could be an Array or Nil, requiring more code. On Thu, Oct 2, 2008 at 4:38 PM, Robert Klemme wrote: > On 02.10.2008 20:35, worthee@gmail.com wrote: > >> 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. >> > > I believe this is a bad idiom. First, the test for "comments" is not > needed because "String === comments" will be false if "comments" is nil. > The statement would have been written much clearer as > > comments = @attributes['comments']) > > if comments.is_a? String > @attributes['comments'] = comments.split(" ") > end > > or > > comments = @attributes['comments']) > @attributes['comments'] = comments.split(" ") if comments.is_a? String > > or > > comments = @attributes['comments']) > @attributes['comments'] = comments.split(" ") if String === comments > > There is only one situation where assignment in a conditional actually > makes code clearer and that is with loops, e.g. > > while line = io.gets > puts line > end > > My 0.02EUR > > Kind regards > > robert > > ------=_Part_14499_25493366.1223015011656--