Каков самый короткий/больше всего идиоматический способ определить, является ли переменная кем-либо из списка значений?

Если Вы находитесь под Leopard OSX, можно дать DTrace попытку.

7
задан the Tin Man 7 October 2016 в 19:18
поделиться

5 ответов

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}
15
ответ дан 6 December 2019 в 09:20
поделиться

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.

3
ответ дан 6 December 2019 в 09:20
поделиться

Я всегда использовал ваш второй пример, if [: a,: b,: c,: d] .include? переменная . Хотя это действительно создает некоторые проблемы с классами, которые перезаписывают == , в большинстве ситуаций, в которых я нуждаюсь (обычно проверка по символам), это совершенно нормально.

1
ответ дан 6 December 2019 в 09:20
поделиться

Как насчет:

 if [:a, :b, :c, :d].index variable
1
ответ дан 6 December 2019 в 09:20
поделиться

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
0
ответ дан 6 December 2019 в 09:20
поделиться
Другие вопросы по тегам:

Похожие вопросы: