仅在ruby中的数组中向Integers添加1

时间:2014-03-26 15:01:53

标签: ruby string integer

我有一个包含混合类的数组:

arr = ["I", "have", 2, "dimes", "and" , 3, "nickels"]

如何在不修改字符串的情况下对数组中的整数执行加法?

预期的输出是,

["I", "have", 3, "dimes", "and" , 4, "nickels"]

3 个答案:

答案 0 :(得分:6)

def add_to_integers(ary, n)
  ary.map { |i| i.is_a?(Integer) ? (i + n) : i }
end

add_to_integers([1, 'foo'], 1)
# => [2, "foo"]

答案 1 :(得分:3)

一个班轮: arr.map!{|element| element.is_a?(Integer) ? element + 1 : element}

答案 2 :(得分:-1)

我认为maprescue是合适的,因为字符串会响应+并且有许多数字类型。

arr.map { |n| begin; n + 1; rescue TypeError; n; end }