我有一个返回此类数据的 mysql 查询:
{"id"=>1, "serviceCode"=>"1D00", "price"=>9.19}
{"id"=>2, "serviceCode"=>"1D01", "price"=>9.65}
我需要根据 serviceCode
的匹配返回 id
字段。
即我需要这样的方法
def findID(serviceCode)
find the row that has the service code and return the ID
end
我在考虑有一个 serviceCodes.each do |row|
方法并循环并基本上去
if row == serviceCode
return row['id']
end
有没有更快/更简单的方法?
最佳答案
您可以使用方法Enumerable#find
:
service_codes = [
{"id"=>1, "serviceCode"=>"1D00", "price"=>9.19},
{"id"=>2, "serviceCode"=>"1D01", "price"=>9.65}
]
service_codes.find { |row| row['serviceCode'] == '1D00' }
# => {"id"=>1, "serviceCode"=>"1D00", "price"=>9.19}
关于mysql - 在 ruby 数组中查找行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25747685/