3 ms·
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:
by raganwald 16y ago
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...
- jseifer 16y agoI really like that find and/or begin pattern. The if user= User.find never really felt right to me either.
- KirinDave 16y agoI 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.
- jamesbritt 16y agoFWIW 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.