News for hackers. Stuff that matters.
Re:Using “and” and “or” in Ruby by raganwald on Monday August 02, 2010 @03:03PM (#1568634)
I use this a lot. I dislike side effects in the subject clause of an if statement, so I used to rewrite:

    if user = User.find(...)
      ...
    end
as:

    user = User.find(...)
    if user
      ...
    end
I then got into the habit of using and:

    user = User.find(...) and begin
      ...
    end
It just seems to resemble something I'd say to a colleague: "user becomes blah blah blah and then we do this with it..." Likewise:

    user = User.find(...) or begin
      user = User.create(...)
      SecurityTheatre.starring(user)
    end
This looks to me like it says "find the user or create the user." The precedence of the words "or" and "and" seems obvious when you think of them as words rather than as operators, while the precedence of operators naturally seems higher/tighter.

JM2C...

Re:Using “and” and “or” in Ruby by KirinDave on Monday August 02, 2010 @03:53PM (#1568815)
I like your find-or-begin pattern, and I've used the or operator to pun that way before as well.

But just a note, the if x = ... is not a side effect unless the variable "x" already exists. There's not problem using that as a pun to get rid of lots of if nesting. Similarly if x &&= ... is very good for avoiding an if-cascade, albeit more obscure and perhaps less performant.

It's too bad there isn't a beautiful way to do monads or the thrush operator in Ruby.

Re:Using “and” and “or” in Ruby by jamesbritt on Monday August 02, 2010 @04:35PM (#1568960)
FWIW

    user = User.find(...) and (
          ...
    )
also works. I find it cleaner. But using begin/end means you can toss a `rescue` in there if you like.
Re:Using “and” and “or” in Ruby by jseifer on Monday August 02, 2010 @03:11PM (#1568669)
I really like that find and/or begin pattern. The if user= User.find never really felt right to me either.