开发者

Simple Ruby 'or' question

开发者 https://www.devze.com 2023-01-29 22:43 出处:网络
开发者_如何学编程In console: @user.user_type = \"hello\" @user.user_type == \"hello\" true @user.user_type == (\"hello\" || \"goodbye\")

开发者_如何学编程In console:

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

How do I write the last statement so it checks to see if @user.user_type is contained in one of the two strings?


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


Enumerable#include? is the idiomatic and simple way to go, but as a side note let me show you a very trivial extension that (I imagine) will please Python fans:

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

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

Sometimes (most of the time, actually) it's semantically more fitting to ask if an object is inside a collection than the other way around. Now your code would look:

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

BTW, I think what you were trying to write was:

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

But we programmers are lazy by nature so better use Enumerable#include? and friends.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号