如何用+ =增加键值

时间:2013-11-21 23:34:13

标签: ruby methods hash key-value

所以我有一个csv文件,我正在拉出来,我无法弄清楚如何在我的一个哈希值中增加一个键的值。我一直收到以下错误,不知道问题是什么?我在其他程序中使用了类似的语法,没有遇到任何麻烦:

rfiv.rb:39:in `block in get_order_num_bags': undefined method `+' for nil:NilClass (NoMethodError)

我的csv文件如下所示: 类型,SKU,RetailPrice,PurchasingPrice 光,1111,5.00,1.50 中,2222,7.50,2.25 粗体,3333,9.75,2.95

我正在运行的ruby文件看起来像这样:

require 'pry'
require 'csv'


@sku_key_menu = Hash.new

CSV.foreach('csvproducts.csv', headers: true) do |row|
  @sku_key_menu[row['SKU']] = {"Type" => row['Name'], "RetailPrice" => row['RetailPrice'], "PurchasingPrice" => row['PurchasingPrice']}
end

@sku_key_menu

def register_display(sku_key_menu) 
  sku_key_menu.each do |sku_key, product_desc_hash|
    puts " #{sku_key} - #{product_desc_hash["Type"]} - $#{product_desc_hash["RetailPrice"]}"
  end
end

register_display(@sku_key_menu) 



def get_order_num_bags
  @single_order = Hash.new(0)
  loop do
    puts "Please enter an SKU or type 'done' to complete order."
    @order_item = gets.chomp.to_s.downcase
    if @sku_key_menu.keys.include?(@order_item) || @order_item == "done"
      break if @order_item == "done"
      puts "Please enter the number of #{@order_item} that you'd like"
      number_of_bags = gets.chomp
      number_of_bags_valid = !!number_of_bags.to_s.match(/\A\d+(\.\d{2})?\z/)
      if number_of_bags_valid
        @single_order[@order_item] = @sku_key_menu[@order_item]
        @single_order[@order_item]['num_bags'] += number_of_bags.to_i  
      else
        puts "Invalid input"
      end
    else
      puts "Invalid input"
    end
  end
  puts @single_order
end

get_order_num_bags

1 个答案:

答案 0 :(得分:2)

@single_order[@order_item]['num_bags']为零,因此您无法添加任何内容。

一个解决方案是:

@single_order[@order_item]['num_bags'] ||= 0
@single_order[@order_item]['num_bags'] += number_of_bags.to_i

||= 0是用于初始化值的常用ruby技术。

另一种解决方案是在您从CSV文件中读取时初始化'num_bags':

CSV.foreach('csvproducts.csv', headers: true) do |row|
  @sku_key_menu[row['SKU']] = {"Type" => row['Name'], "RetailPrice" => row['RetailPrice'], "PurchasingPrice" => row['PurchasingPrice'],
    'num_bags' => 0}
end