Say I have a Ruby class, Flight
. Flight
has an attr_accessor :key
on it. If there's an array of instances of this class: flights = [flight1, flight2, flight3]
, I have a "target key", say "2jf345", and I want to find a flight based on it's key, from that array - what sort of code should I use?
假设我有一个Ruby类,Flight。 Flight上有一个attr_accessor:键。如果有这个类的实例数组:flights = [flight1,flight2,flight3],我有一个“目标键”,比如说“2jf345”,我想找一个基于它的键的飞行,从那个数组 - 什么我应该使用哪种代码?
This is the code I was going to use:
这是我要使用的代码:
flights[flights.map { |s| s.key }.index(target_key)]
航班[flights.map {| s | s.key} .index(target_key)]
But it seems like with Ruby, there should be a simpler way. Also, the code above returns an error for me - `[]': no implicit conversion from nil to integer (TypeError)
. I assume this means that it's not returning an index at all.
但是看起来像Ruby,应该有一个更简单的方法。此外,上面的代码为我返回一个错误 - “[]”:没有从nil到整数的隐式转换(TypeError)。我认为这意味着它根本没有返回索引。
Thanks for any help.
谢谢你的帮助。
1 个解决方案
#1
30
You can just use find
to get the Flight object, instead of trying to use index
to get the index:
您可以使用find来获取Flight对象,而不是尝试使用index来获取索引:
flights.find {|s| s.key == target_key }
However your error message suggests that index(target_key)
returns nil
, which means that you don't actually have a flight with the key you're looking for, which means that find
will return nil
as well.
但是,您的错误消息表明index(target_key)返回nil,这意味着您实际上没有包含您正在查找的键的航班,这意味着find也将返回nil。
#1
30
You can just use find
to get the Flight object, instead of trying to use index
to get the index:
您可以使用find来获取Flight对象,而不是尝试使用index来获取索引:
flights.find {|s| s.key == target_key }
However your error message suggests that index(target_key)
returns nil
, which means that you don't actually have a flight with the key you're looking for, which means that find
will return nil
as well.
但是,您的错误消息表明index(target_key)返回nil,这意味着您实际上没有包含您正在查找的键的航班,这意味着find也将返回nil。