【问题标题】:In Ruby, if I have an array, how can I replace any negative values with "0"?在 Ruby 中,如果我有一个数组,如何用“0”替换任何负值?
【发布时间】:2020-07-30 00:10:41
【问题描述】:

假设我有以下数组:

array_sample = [2, 7, 3, -5, 2, -6]

有没有办法将“-5”和“-6”替换为 0(或任何其他潜在的负值)?

我尝试了以下似乎不起作用的方法:

for i in array_sample
   if array_sample[i] < 0
       array_sample[i] = 0
end

任何建议都将不胜感激,因为这看起来很简单!

【问题讨论】:

  • i 不是你想象的那样。只需在for i in array_sample 下方插入puts i 即可进行调查。
  • 另外,使用 .map.each 比使用 ruby​​ 中的循环更好:stackoverflow.com/a/31263749/8031815

标签: arrays ruby


【解决方案1】:

这是另一个sn-p:

array_sample.map!{|item| [0, item].max}

这会将每个数组值替换为原始项目或 0,以较大者为准。如果您想要一个不会改变当前数组的新数组(通常是个好主意),您可以使用map 而不是map!

【讨论】:

  • 由于 OP 明确要求替换,您应该在示例中使用 map!
【解决方案2】:

试试这个

array_sample = [2, 7, 3, -5, 2, -6]

array_sample.map! { |e| e > 0 ? e : 0 }

回应

[2, 7, 3, 0, 2, 0]

【讨论】:

    【解决方案3】:

    您可以尝试使用地图

    array_sample.map do |int|
       if (int < 0)
          0
       else 
          int
       end
    end
    

    【讨论】:

    • 是的,但是使用map! 或将其分配给一个新的(或相同的)变量
    • map 是最理想的方式。但是,也许尝试条件表达式?说,array_sample.map { |item| item &lt; 0 ? 0 : item }
    【解决方案4】:

    要将您的示例直接转换为正确的代码,您可以这样做:

    array_sample.each_with_index do |value, index|
      if value < 0
        array_sample[index] = 0
      end
    end
    

    但其他答案可能更惯用。

    请注意,ruby 默认情况下不使用数字进行迭代,就像类 c 语言通常那样。大多数时候,ruby 会返回每个项目,而不是索引,然后您必须查找数字。 (除非您要求,否则它会隐藏索引)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-08
      • 2022-07-21
      • 2021-01-27
      • 1970-01-01
      • 1970-01-01
      • 2016-11-04
      • 2017-01-18
      • 2017-04-22
      相关资源
      最近更新 更多