【问题标题】:Finding a value in an array of class objects [closed]在类对象数组中查找值[关闭]
【发布时间】:2016-06-09 03:06:01
【问题描述】:

有没有办法在类对象数组中找到 的值。那么一旦发现它被包含,你能找到它所在的数组中的什么位置吗?例如

class SomeClass
def initialize(value,otherData)
      @value = value
      @otherData = otherData
 end
end

x = 0
otherData = "foo"
list = Array.new
while (x < 3)
     list.push SomeClass.new(x,otherData)
     x += 1
end

我想找到 list[x].value where value=2 并找出数组中的位置。

【问题讨论】:

  • 您的代码无效。什么是value 方法?您的驼峰式局部变量给人的印象非常糟糕。
  • 我认为你只需要遍历对象数组,查看对象中的值,然后从那里开始
  • 代码不是无效的,它只是示例,不想争论 camelCase 与 underscore_case

标签: arrays ruby sorting object


【解决方案1】:

如果 SomeClass 有一个value 方法,一个明显的方法是:

ix = list.find_index { |sc| sc.value == 2 }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-21
    • 1970-01-01
    • 2022-08-18
    • 2021-10-19
    • 2021-08-17
    • 2022-11-04
    • 1970-01-01
    • 2014-11-27
    相关资源
    最近更新 更多