Если Вы находитесь под Leopard OSX, можно дать DTrace попытку.
Actually, #include?
does use ==
. The problem arises from the fact that if you do
[:a].include? foo
it checks :a == foo
, not foo == :a
. That is, it uses the ==
method defined on the objects in the Array, not the variable. Therefore you can use it so long as you make sure the objects in the array have a proper ==
method.
In cases where that won't work, you can simplify your statement by removing the select
statement and passing the block directly to any
:
if [:a, :b, :c, :d].any? {|f| variable == f}
It looks like Array#include?
does use ==
:
>> class AString < String
>> def ==(other)
>> self[0] == other[0]
>> end
>> end
>> asdf = AString.new "asdfg"
=> "asdfg"
>> b = AString.new 'aer'
=> "aer"
>> asdf == b
=> true
>> [asdf].include? b
=> true
The Array#include?
documentation also explains this.
Я всегда использовал ваш второй пример, if [: a,: b,: c,: d] .include? переменная
. Хотя это действительно создает некоторые проблемы с классами, которые перезаписывают ==
, в большинстве ситуаций, в которых я нуждаюсь (обычно проверка по символам), это совершенно нормально.
What you are really doing is seeing if variable is a member of the set [:a,:b,:c,:d]
so semantically that maps to the include?
method.
The problem you encounter is due to the duck-typing nature of Ruby so if you want to get around that why not first convert to a symbol:
if [:a, :b, :c, :d].include? variable.to_sym