我正试图找到一种方法来通过以下测试,但我最终仍然在循环中使用循环,这是非常糟糕的。有人可以帮忙吗?这是测试:
require 'spec_helper'
describe Promotion_Check do
let(:check) { Promotion_Check.new rules_list }
let(:item_rule) { {rule_type: "item", item_code: 1, number_of_items: 2, new_item_price: 8.50} }
let(:total_rule) { {rule_type: "total", total_price_break: 60.00, discount_percentage: 10} }
let(:rules_list) { [ 1 => item_rule, 2 => total_rule ] }
describe "#applicable_item_rules" do
it "finds the rules that apply to the baskets items" do
item_code = 1
count = 2
expect(check.applicable_item_rules(item_code, count)).to eq [item_rule]
end
end
end
基本上,我想搜索像这样的哈希数组:
rules_list = [ 1 => {rule_type: "item", item_code: 1, number_of_items: 2, new_item_price: 8.50}, 2 => {rule_type: "item", item_code: 2, number_of_items: 4, new_item_price: 7.50}]
对于具有匹配值的任何内容:item_code和:number_of_items并将该值推送到数组中。
感谢您的帮助
答案 0 :(得分:0)
因为Ruby很有帮助
rules_list = [
1 => {rule_type: "item", item_code: 1, number_of_items: 2, new_item_price: 8.50},
2 => {rule_type: "item", item_code: 2, number_of_items: 4, new_item_price: 7.50}
]
最终成为:
=> [{
1=>{:rule_type=>"item", :item_code=>1, :number_of_items=>2, :new_item_price=>8.5},
2=>{:rule_type=>"item", :item_code=>2, :number_of_items=>4, :new_item_price=>7.5}
}]
这是一个长度为1的数组,包含一个长度为2的散列。你最好这样做:
rules_list = [
{rule_type: "item", item_code: 1, number_of_items: 2, new_item_price: 8.50},
{rule_type: "item", item_code: 2, number_of_items: 4, new_item_price: 7.50}
]
并像这样查询:
rules_list.select { |rule| rule[:item_code] == 1 && rule[:number_of_items] == 2 }
=> [{:rule_type=>"item", :item_code=>1, :number_of_items=>2, :new_item_price=>8.5}]