Rick
Rick

Reputation: 49

Is it considered good practice to use AND as a logic gate?

I'm both new to ruby and to programming in general. While working my way thru "The Well-Grounded Rubyist" book I came across this expression from the set.rb standard library:

enum.nil? and return

It seems like an odd (but clever) way to do this:

return unless enum.nil?

It that a common technique? Also, why do it that way? Am I missing something?

Here's the full code snippet:

def initialize(enum = nil, &block)
  @hash ||= Hash.new

  enum.nil? and return

  if block
    do_with_enum(enum) { |o| add(block[o]) }
  else
    merge(enum)
  end
end

Upvotes: 2

Views: 122

Answers (1)

mralexlau
mralexlau

Reputation: 2003

Per Avdi Grimm's article on this subject, the keywords and and or are used for flow control operators in ruby, as opposed to being boolean operators.

You are correct that enum.nil? and return is the same as return unless enum.nil?. I would agree with you that in this case using unless would be more readable.

This pattern isn't uncommon in ruby, the reason it's done this way is to show intention of flow control by making use of the low precedence of the and operator. Since this operator has low precedence, it allows you to add more actions chained on with subsequent and's without conflicting with other operations that may be done in that same line of code. However, most would consider explicitly gating a condition with an if the preferable way to control flow.

Upvotes: 1

Related Questions