gpt4 book ai didi

ruby-on-rails - 在 Ruby 中搜索项目的对象数组

转载 作者:数据小太阳 更新时间:2023-10-29 07:46:08 24 4
gpt4 key购买 nike

我正在尝试在对象数组中搜索一个值,但无法使 find_index 正常工作。在下面的代码中,我试图在数组中搜索名称 (joseph)。这是最好的方法吗?我想在搜索并找到它后返回该对象。

name = "joseph"

array = [{"login":"joseph","id":4,"url":"localhost/joe","description":null},
{"login":"billy","id":10,"url":"localhost/billy","description":null}]

arrayItem = array.find_index {|item| item.login == name}

puts arrayItem

最佳答案

您的数组包含一个散列,其键是符号(在散列中,key: value:key => value 的简写)。因此,您需要将 item.login 替换为 item[:login]:

name = "joseph"

array = [{"login":"joseph","id":4,"url":"localhost/joe","description":nil},
{"login":"billy","id":10,"url":"localhost/billy","description":nil}]

arrayIndex = array.find_index{ |item| item[:login] == name }

puts arrayIndex

上面的代码检索查找对象在数组中的索引。如果您想要对象而不是索引,请使用 find 而不是 find_index:

arrayItem = array.find{ |item| item[:login] == name }

另请注意,在 Ruby 中,null 实际上称为 nil

关于ruby-on-rails - 在 Ruby 中搜索项目的对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32378613/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com