我从xlsx文件中提取数据,如下所示:
[6, 2]=>"Comment", [6, 3]=>"Complaint", [6, 4]=>"Enquiry"
我想搜索数组并返回括号中第二个数字的值。即,搜索Complaint
应该返回3
。任何帮助表示赞赏。
NB - 根据对数组的评论进行了更新。在OP中删除了字符串转换。
require 'roo'
today_file=(File.dirname(__FILE__) + '/output/today-report.xlsx')
def by_value(data, value)
found = data.find do |k, v|
v == value
end
found and found[0][1]
end
data = Roo::Excelx.new (today_file)
output = by_value(data, "Complaint").inspect
puts output
运行时,返回' nil'
此数组的输出采用以下形式:
{[1, 1]=>"YESTERDAY - 02/10/14", [1, 4]=>"Another comment below the fold - scroll down", [2, 1]=>"Yesterday we received 11 regarding the service.", [4, 1]=>"TYPE", [6, 1]=>"", [6, 2]=>"Comment", [6, 3]=>"Complaint", [6, 4]=>"Enquiry", [6, 5]=>"Total (Type)", [7, 1]=>"Editorial and other queries", [7, 2]=>1.0, [7, 3]=>7.0,...}
答案 0 :(得分:0)
如果您是Ruby新手,那么您需要花时间熟悉Enumerable库。它有大量用于操作和提取数据的工具。
在这种情况下,find
完成工作:
def by_value(data, value)
# Find the key/value pair where the value matches
found = data.find do |k, v|
v == value
end
# If one of these was found, pull the second number from the key
found and found[0][1]
end
data = {[6, 2]=>"Comment", [6, 3]=>"Complaint", [6, 4]=>"Enquiry"}
puts by_value(data, "Complaint").inspect
# => 3
值得注意的是,由于您正在进行线性搜索,因此这是一个相对较慢的操作。如果这种情况经常发生,你可以将其反转,以便更快地进行搜索:
def by_value(data, value)
found = data[value]
found and found[1]
end
# Using Hash#invert switches the keys and values so you can now look-up by value
data = {[6, 2]=>"Comment", [6, 3]=>"Complaint", [6, 4]=>"Enquiry"}.invert
puts by_value(data, "Complaint").inspect
# => 3
答案 1 :(得分:0)
这是一个奇怪的要求。这是怎么做的。
word = "Complaint"
data_string[/, (\d+)\]=>"#{Regexp.escape(word)}"/, 1] # => "3"