franzejr / best-ruby

Ruby Tricks, Idiomatic Ruby, Refactoring and Best Practices
http://franzejr.github.io/best-ruby/
2.39k stars 219 forks source link

Inner assignment conditional is a pretty bad example... #39

Closed jtmarmon closed 8 years ago

jtmarmon commented 8 years ago

Why would you ever do

retval = if vals.any?
           do_something(vals)
         else
           do_something_different
         end

over

retval = vals.any? ? do_something(vals) : do_something_different

I think the inner assignment conditional only makes sense when more logic needs to be performed inside the conditions

franzejr commented 8 years ago

Nice, @jtmarmon, we can put that in one line exactly. My point here was to show that we can also use

retval = if vals.any?
           do_something(vals)
         else
           do_something_different
         end

rather than:

if vals.any?
          retval =  do_something(vals)
 else
           retval = do_something_different
end

But, for sure it's best your solution in one line. What about we put the one line solution and also this solution? What do you think?

jtmarmon commented 8 years ago

Well I think you could best refine the page to - rather than focusing on specific examples - showing the multitude of ways you can be "lispy" in ruby (as ruby is quite lisp inspired).

Examples:

retval = if vals.any?
           do_something(vals)
         else
           do_something_different
         end
retval = case my_val
         when "foo"
           2
         when "bar"
           3
         else
           5
         end
retval = vals.any? ? do_something(vals) : do_something_different
retval = foo unless bar

etc. generally performing assignment on expressions that use first class operators. this was just a few off the top of my head. if you like the idea for the revision i'd be happy to PR it

franzejr commented 8 years ago

I liked the idea! I think the multitude of ways is nice! And we can have the one line and also those examples you did. Looking forward for your PR.

Thanks! :+1:

jtmarmon commented 8 years ago

on it. any ideas for the title of the article?

franzejr commented 8 years ago

My idea at the beginning it was "inner assignment", because I would like to remove the assignment inside my conditional. Since, we are still working with assignments, conditionals and we're trying to do the same thing... Why not keep the title or something like "Conditional Assignments" ?

jtmarmon commented 8 years ago

yeah i like it

franzejr commented 8 years ago

:+1: looking forward for your PR!

jtmarmon commented 8 years ago

40