views:

49

answers:

1

if the code is

do_more ||= true

then when false is passed in, it becomes

do_more = false || true

and therefore will still be true. So this is one case where foo ||= default_value won't work? In this case it will need to be

do_more = true if !defined? do_more

?

A: 

More generally, foo ||= default_value never works if a valid value for foo is false.

foo ||= default_value is only a valid pattern when all valid values are interpreted as boolean TRUE.

Your statement of do_more == true if !defined? do_more should use the assignment operator, I presume a typo: do_more = true if !defined? do_more

Maybe better would be do_more = true unless defined? do_more

That looks ok to me, but you need to test to ensure that it works correctly.

If your param is coming in from an HTML form, then the undefined case is actually a zero length string, "". If that is your situation, then you'd want:

do_more = true if do_more == ''

I'd also suggest a comment # set default

Larry K
yes it was a typo. so in other words, if you ever need to pass in a `nil` or `false`, you cannot use `foo ||= some_value`. I am not so used to `unless` since I have been using `if` for 28 years. I need an extra few seconds to understand it as opposed to immediately if using `if`
動靜能量
`do_more = true unless defined? do_more` won't work: see [In Ruby why won't `foo = true unless defined?(foo)` make the assignment?](http://stackoverflow.com/questions/2291646/in-ruby-why-wont-foo-true-unless-definedfoo-make-the-assignment)
Andrew Grimm
@Jian Lin: I hear you re if. But more importantly for this situation, see @Andrew Grimm's comment. In similar circumstances, I've redefined variables to be in the negative so that the omitted value (nil) can be used as the default. Here, that'd be "do_no_more" rather than "do_more". @Andrew: +1 Thanks.
Larry K