如何使用ruby在字符串数组中添加整数?

时间:2015-05-13 05:43:31

标签: arrays ruby

我在方法中使用以下ruby代码创建了一个数组:

array[i] = {:key => response.body['results'][i]['path']['key'],  
              :value => response.body['results'][i]['value'],
              :epoch_time => response.body['results'][i]['path']['reftime'] / 1000}
array[i][:collection] = response.body['results'][i]['path']['collection']

我想要另一种方法.enumerate_array或其他方法通过追加"我 - "其中i是数组的相应索引值。

例如,array[0][:value] = "this was the first answer"

然后:

array = enumerate_array(array)

=> array[0][:value] = "0 - this was the first answer"

感谢。

5 个答案:

答案 0 :(得分:1)

如果你有以下带有哈希的数组:

[{ value: "foo" }, { value: "bar" }, { value: "baz" }]

您需要以下输出:

[{ value: "0 - foo" }, { value: "1 - bar" }, { value: "2 - baz" }]

你可以这样做:

def enumerate_array(array)
  array.each_with_index do |hash, index|
    hash[:value] = "#{index} - #{hash[:value]}"
  end
end

答案 1 :(得分:0)

制作原始哈希的副本:

def enumerate_array(array)
  array.map.with_index { |h, i| h.merge({value: "#{i} - #{h[:value]}"}) }
end

改变原始哈希:

def enumerate_array!(array)
  array.each_with_index { |h, i| h[:value] = "#{i} - #{h[:value]}" }
end

答案 2 :(得分:0)

arr = [{ value: "dog" }, { value: "cat" }, { value: "pig" }]

如果要改变arr

arr.each_index { |i| arr[i][:value] = "#{i} - #{arr[i][:value] }" }
  #=> [{:value=>"0 - dog"}, {:value=>"1 - cat"}, {:value=>"2 - pig"}] 
arr
  #=> [{:value=>"0 - dog"}, {:value=>"1 - cat"}, {:value=>"2 - pig"}] 

如果arr不被改变(重置arr后):

arr.each_index.with_object([]) { |i,a| a << { value: "#{i} - #{arr[i][:value] }" } }
  #=> [{:value=>"0 - dog"}, {:value=>"1 - cat"}, {:value=>"2 - pig"}] 
arr 
  #=> [{:value=>"dog"}, {:value=>"cat"}, {:value=>"pig"}] 

答案 3 :(得分:0)

def enumerate_array(array)
  array.each_with_index do |hash, index|
      hash.each_pair { |key, value| hash[key] = "#{index} - #{value}" }
  end
end

答案 4 :(得分:-1)

如果你正在使用ruby 2.x,你可以使用map map和with_index来使它成为一个单行:

[super init]