Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 缩短每个循环_Ruby On Rails_Ruby - Fatal编程技术网

Ruby on rails 缩短每个循环

Ruby on rails 缩短每个循环,ruby-on-rails,ruby,Ruby On Rails,Ruby,我有一个循环: data.each do |variant| code = prices[variant["vcode"].to_sym] if code.nil? reg = sell = sale = " " else reg = code[:reg] sell = code[:sell] sale = code[:sale] end variant["reg"] = reg variant["sell"] = sell variant

我有一个循环:

data.each do |variant|
code = prices[variant["vcode"].to_sym]
  if code.nil?
    reg = sell = sale = " "
  else
    reg = code[:reg]
    sell = code[:sell]
    sale = code[:sale]
  end
  variant["reg"] = reg
  variant["sell"] = sell
  variant["sale"] = sale
现在,我想缩短代码,就像我以前对
reg=sell=sale=“”
所做的那样:

reg = " "
sell = " "
sale = " "
我也想和你一起做

reg = code[:reg]
sell = code[:sell]
sale = code[:sale]

我试过这个:

  def price_values
    %i[reg sell sale]
  end
替换

reg = code[:reg]
sell = code[:sell]
sale = code[:sale]

但它返回
nil
。我做错了什么

data.each do |variant|
  code = prices[variant["vcode"].to_sym]
  %w|reg sell sale|.each do |e|
    variant[e] = code.nil? ?  " " : code[e.to_sym]
  end
end
或者,更好的是,使用默认哈希函数

data.each do |variant|
  code =
    prices[variant["vcode"].to_sym] ||
    Hash.new { |h, k| h[k] = " " }

  %w|reg sell sale|.each do |e|
    variant[e] = code[e.to_sym]
  end
end
或者,更好的是,使用默认哈希函数

data.each do |variant|
  code =
    prices[variant["vcode"].to_sym] ||
    Hash.new { |h, k| h[k] = " " }

  %w|reg sell sale|.each do |e|
    variant[e] = code[e.to_sym]
  end
end


请参阅。

reg,sell,sale=code。在(*price\u values)处的值。
注意
reg=sell=sale=“”
与您以前的值不完全相同。尝试
reg为什么要先分配给局部变量,然后再将其值重新分配给
变量
哈希?这看起来太复杂了。为什么用
来表示缺少的值,而不是通常的
nil
?你的代码应该实现什么?看起来它做得有点太多了。@Stefan我收集的数据都将写在xlsx文档中,要求我提供一个空值,如果它为零。
reg,sell,sale=code.values在(*price\u values)
注意
reg=sell=sale=“
与您以前的情况不完全相同。尝试
reg为什么要先分配给局部变量,然后再将其值重新分配给
变量
哈希?这看起来太复杂了。为什么用
来表示缺少的值,而不是通常的
nil
?你的代码应该实现什么?看起来它做得有点太多了。@Stefan我收集的数据都将写入xlsx文档,要求我提供一个空值,如果它是nil.yesp。虽然这整件事有些让我不安,但我不能把我的手指放在上面。这是奇怪的默认值吗耸耸肩:@SergioTulentsev,我猜是重新分配本身。我会选择一些
data.prices.code
,而不是从那里复制一堆数据。Getter可能会自己返回
。是的。虽然这整件事有些让我不安,但我不能把我的手指放在上面。这是奇怪的默认值吗耸耸肩:@SergioTulentsev,我猜是重新分配本身。我会选择一些
data.prices.code
,而不是从那里复制一堆数据。Getter可能会自己返回
data.each do |variant|
  code =
    prices[variant["vcode"].to_sym] ||
    Hash.new { |h, k| h[k] = " " }

  %w|reg sell sale|.each do |e|
    variant[e] = code[e.to_sym]
  end
end
data.each do |variant|
  f = prices[variant["vcode"].to_sym] || {}
  [:reg, :sell, :sale].each { |k| variant[k.to_s] = f.fetch(k,' ') }
end