这是我的代码:
def return_rider_values(pol_option, pro_endorsement, prop_coverage, *par)
rider_values
par.each do |p|
rider_values << RiderValue.find_all_by_rider_id(p)
end
rider_hash = { }
rider_values.each do |rv|
if rv.attributes["name"].downcase == "yes"
rider_hash.merge!({par[0].to_s => rv.attributes['id'].to_s})
elsif rv.attributes["position"] == pol_option.to_i && rv.attributes["rider_id"] == par[1]
rider_hash.merge!({par[1].to_s => rv.attributes["id"].to_s})
elsif rv.attributes["position"] == prop_coverage.to_i && rv.attributes["rider_id"] == par[2]
rider_hash.merge!({par[2].to_s => rv.attributes["id"].to_s})
elsif rv.attributes["position"] == pro_endorsement.to_i && rv.attributes["rider_id"] == par[3]
rider_hash.merge!({par[3].to_s => rv.attributes["id"].to_s})
end
end
rider_hash
end
输出如下:
rider_hash #=> '22' -> 58
'23' -> 61
'25' -> 66
'26' -> 68
我很期待,显然需要它,因为它不能在以后的工作中使用:
rider_hash #=> '22' -> '58'
'23' -> '61'
'25' -> '66'
'26' -> '68'
我不知道为什么程序后面的查找函数要求id是字符串而不是int。我知道它确实如此,而且由于许多其他方法都使用它,我无法改变它。
我在哈希键和值上都有to_s
。我意识到在Ruby 1.9中to_s
是inspect
的别名,但即使在Hash文档中它也表示,inspect or to_s
应该“将此哈希的内容返回为一根绳子。“
那么为什么只将键作为字符串返回?
答案 0 :(得分:0)
你有一系列哈希值,所以试试这个:
def return_rider_values
par = [1,2,3,6]
rider_hash = {}
rider_values = [element1: {:attributes => {:id => 1, :name => 'yes', :position => 1, :rider_id => 1}},
element2: {:attributes => {:id => 2, :name => 'no', :position => 2, :rider_id => 2}},
element3: {:attributes => {:id => 3, :name => 'something', :position => 1, :rider_id => 3}},
element4: {:attributes => {:id => 4, :name => 'something_else', :position => 2, :rider_id => 6}}]
rider_values.each_with_index do |hash, idx|
rider_values[idx].each_pair do |k, v|
if v[:attributes][:name].downcase == "yes"
rider_hash.merge!({par[0].to_s => v[:attributes][:id].to_s})
elsif v[:attributes][:position] == 2 && v[:attributes][:rider_id] == par[1]
rider_hash.merge!({par[1].to_s => v[:attributes][:id].to_s})
elsif v[:attributes][:position] == 3 && v[:attributes][:rider_id] == par[2]
rider_hash.merge!({par[2].to_s => v[:attributes][:id].to_s})
elsif v[:attributes][:position] == 4 && v[:attributes][:rider_id] == par[3]
rider_hash.merge!({par[3].to_s => v[:attributes][:id].to_s})
end
end
end
rider_hash
end
test = return_rider_values
puts test
输出:#=> {"1"=>"1", "2"=>"2"}
答案 1 :(得分:0)
我最终得到了我想要的东西:
rider_hash.each{ |_,v| v.replace "'#{v}'"}
但这似乎是一种肮脏的解决方案。