From: Jamis Buck Date: 2004-01-14T03:12:54+09:00 Subject: Re: Warnings on assignments in conditionals? David Heinemeier Hansson wrote: >> Apologies in advance if you already understand this distinction, but >> it is one that has tripped many a programmer, even those who should >> know better ;) If you indeed mean to assign the value to 'a' (as in >> the first example), you can probably avoid the warning from Ruby by >> breaking this into two lines, e.g. >> >> a = 1 >> if a then true else false end > > > I did understand the distinction, I was just puzzled that Ruby would > throw a warning on something that worked as intended and as advertised > although it would probably be considered ambigious. > > But in this real-life example, it doesn't that seem ambigious (and > hence useful): > > def apply_coupon(code) > if @coupon = Coupon.find_by_code(code) then true else false end > end > > I guess I'm questioning when, or even if, the parser should throw > warnings on something that it considers to be bad style. > > / David For what its worth, you can get the same effect, without the warning, like this: @coupon = Coupon.find_by_code(code) and true or false Not nearly as readable, but... Alternatively, you can take advantage of the fact that Ruby treats all values as 'true' EXCEPT 'nil' and 'false' (which are always false), you could just say def apply_coupon( code ) @couple = Coupon.find_by_code(code) end This would then return the value of @coupon, which (if null or false) would be false, and otherwise may be treated as a 'true' value. -- Jamis Buck jgb3@email.byu.edu ruby -h | ruby -e 'a=[];readlines.join.scan(/-(.)\[e|Kk(\S*)|le.l(..)e|#!(\S*)/) {|r| a << r.compact.first };puts "\n>#{a.join(%q/ /)}<\n\n"'