如何检查 Ruby 数组中是否存在具有特定属性的对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11376746/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 03:39:24  来源:igfitidea点击:

How can I check if an object with specific property exists in a Ruby array

ruby-on-railsruby

提问by gabitzish

I have an array of objects *and the object looks something *like this {seat_id, room_id, date_created};
I want to find if in that array there is an object which has seat_id equal to a specific value. How can I do that?

我有一个对象数组 * 并且对象看起来像这样 *{seat_id, room_id, date_created};
我想查找该数组中是否有一个对象的座位 ID 等于特定值。我怎样才能做到这一点?

回答by davidrac

arr.any?{|a| a.seat_id == "value"}

回答by Linuxios

Here:

这里:

arr.find_index {|item| item.seat_id == other.seat_id}

回答by Sandip Mondal

arr.map{|a| a.seat_id == "value"}

It will return array of true and false value, true value are matching value.

它将返回真假值数组,真值是匹配值。