mysql - 在 ruby​​ 数组中查找行

标签 mysql ruby

我有一个返回此类数据的 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/

相关文章:

mysql - 如何在插入重复更新mysql查询时使用case/if else

mysql - 在mysql中选择非字母记录

php - Mysql 加入 1 行与多行 - 组 concat 或 php?

ruby-on-rails - wicked_pdf 在 unicode pdf 转换 (ruby) 上显示未知字符

ruby - Controller 方法 Rails 5 上的 NoMethodError

ruby-on-rails - 在 rails 的 fast_jsonapi 中将 current_user 和链接一起传递

MYSQL 使用 mysqlimport 自动从文件夹插入 csv 文件

mysql - 多次更新mysql

ruby - 为什么 4.1%2 使用 Ruby 返回 0.0999999999999996?但是 4.2%2==0.2

java - 动态查找字符串以寻址串行端口