Skip to content

Instantly share code, notes, and snippets.

@jonleighton
Created March 5, 2013 18:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonleighton/5092937 to your computer and use it in GitHub Desktop.
Save jonleighton/5092937 to your computer and use it in GitHub Desktop.
# This style of code is a complete abomination and you should never do it!
my_var = if whatever?
thing
else
other_thing
end
@jonleighton
Copy link
Author

What should you do instead? Make another method:

def whatever_thing
  if whatever?
    thing
  else
    other_thing
  end
end

my_var = whatever_thing

Or just repeat the LHS, it's not that bad:

if whatever?
  my_var = thing
else
  my_var = other_thing
end

@carlosantoniodasilva
Copy link

I also dislike it =(. What it seems ok doing is unindenting everything:

my_var = if whatever?
  thing
else
  other_thing
end

I far prefer this than everything right aligned with all that space floating around as you showed.

@mhfs
Copy link

mhfs commented Mar 5, 2013

I second @carlosantoniodasilva on this. Not thrilled about it but bearable. Too bad VIM insists on the gist example indentation. Do you know if it's possible to change that?

@AndrewRadev
Copy link

I dislike it as well. We had a discussion over this in vim-ruby, and in the end, decided against changing the current behaviour with the hanging indent (so no, @mhfs, it's currently not possible to change this). My personal preference used to be @carlosantoniodasilva's, but I've noticed that this way the assignment clause tends to become difficult to notice. These days I just repeat the LHS.

One interesting solution @tpope came up with is this:

@foo =
  if @bar.nil?
    :one
  else
    :two
  end

This works out of the box in vim-ruby. Recently, I've started to reconsider this style myself. It's also a reasonable way to do this:

@foo ||=
  begin
    foo = 'bar'
    foo.upcase
  end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment