我有一个具有独特元素的数组.有没有办法在不使用索引值的情况下用另一个值替换它中的某个值?
例子:
array = [1,2,3,4] if array.include? 4 # "replace 4 with 'Z'" end array #=> [1,'Z'] hash = {"One" => [1,4]} if hash["One"].include? 4 # "replace 4 with 'Z'" end hash #=> {"One" => [1,'Z']}
解决方法
p array.map { |x| x == 4 ? 'Z' : x } # => [1,'Z']