Question

Ruby provides unless and elsif statements. It seems natural to assume that there would be a similar elsunless statement, but there is not. Is there a specific reason for this?

To illustrate, this statement would allow for code like this.

unless broken
  # do something
elsunless done
  # do something else
end

I'm aware that this code can be rewritten to use if and elsif, but in some cases using unless is clearer.

Était-ce utile?

La solution

The logic behind if / else statements usually is:

Having one exception:

if exception_a
  # do exception stuff
else
  # do standard stuff
end

unless exception_a
  # do standard stuff
else
  # do exception stuff
end

Adding unless in this case can be very useful, as you can switch around your code. What I also love about unless is that you can solely do your standard stuff while checking for an exception. (the else block can be left out)

Having multiple exceptions:

Here comes the tricky part:

if exception_a
  # do exception stuff a
elsif exception_b
  # do exception stuff b
else
  # do standard stuff
end

unless exception_a
  # do standard stuff
elsunless exception_b
  # do ???
else
  # do exception stuff
end

Besides being totally unreadable, I couldn't find a logical meaning to the elsunless block: What code would you put in there? I still have no idea if that would be some exception stuff or standard code.

Maybe you can explain further what code you would use in such a block.

Autres conseils

Ruby already provides if, else, elsif, and unless, so is there really a need to for elsunless? It looks like a hulking mammoth in a code. I think Matz doesn't see a reason to add the statement into a the ruby syntax. Additionally, some of ruby coders investigate a ruby coding standard that excludes unless statement usage, which was inherited from Perl.

As for me, I would completely remove the unless keyword from the language.

Have a look at the styling guide

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top