Simple Ruby 'or' question

前端 未结 2 1320
栀梦
栀梦 2020-12-18 16:20

In console:

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

How do I

相关标签:
2条回答
  • 2020-12-18 16:44
    ["hello", "goodbye"].include? @user.user_type
    
    0 讨论(0)
  • 2020-12-18 16:47

    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 讨论(0)
提交回复
热议问题