【问题标题】:Ruby - include? returning false when object is indeed in array红宝石 - 包括?当对象确实在数组中时返回 false
【发布时间】:2014-05-27 21:28:45
【问题描述】:
my_hash = Hash.new{|h,k| h[k] = []}
name = 'John'
my_hash[name] << '7'
my_hash[name] << '9'
name = 'Jane'
my_hash[name] << '7'
my_hash[name] << 'J'

array_info = my_hash.values_at('John')
puts array_info.class                   => array 
array_info.each do |ele|
   puts ele                             => 7, 9
end
removed = array_info.include?('7')
puts removed                           => false ??!?!?????

array_info 刚刚打印了 7 作为数组中的一个元素,所以我们知道它存在。那么为什么 array_info.include?('7') 不会返回 true 呢?

【问题讨论】:

    标签: ruby arrays hash include


    【解决方案1】:

    看看array_info。 Puts-ing 它表明您的 ele 值确实在该数组中,但是您的数组嵌套在另一个数组中。

    removed = array_info.first.include?('7')
    

    将返回 true。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-28
      • 2023-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多