简体   繁体   中英

Add 1 only to Integers in an array in ruby

I have an array which contains mixed classes:

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

How do I perform addition on the integers in the array without modifying the strings?

The expected output is,

["I", "have", 3, "dimes", "and" , 4, "nickels"]
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"]

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM