Simple Ruby 'or' Question

In the console:

@user.user_type = "hello"
@user.user_type == "hello"
  true
@user.user_type == ("hello" || "goodbye")
  false

How to write the last statement so that it checks whether it is contained @user.user_typein one of two lines?

+1
source share
2 answers
["hello", "goodbye"].include? @user.user_type
+8
source

Enumerable#include? is an idiomatic and easy way, but as an additional note, let me show you a very trivial extension that (I think) Python fans will like:

class Object
  def in?(enumerable)
    enumerable.include?(self)
  end
end

2.in? [1, 2, 3]  # true
"bye".in? ["hello", "world"] # false   

Sometimes (in most cases, actually) it is semantically more appropriate to ask whether an object is inside a collection than vice versa. Your code will now look:

@user.user_type.in? ["hello", "goodbye"]

By the way, I think you tried to write:

@user.user_type == "hello" || @user.user_type == "goodbye"

But we programmers are lazy in nature, so we better use Enumerable#include?friends too.

+7

All Articles