My String数组是这样的
arr = ["a", "apple", "b", "banyan", "banana", "c", "cat"]
我想将baynan合并到banana中,所以我的数组看起来像这样,我可以创建一个hashmap
arr = ["a", "apple", "b", "banyanbanana", "c", "cat"]
hash_arr = Hash[*arr]
但我仍然没有想法通过ruby在同一个数组中合并特定的两个相邻值。合并没有固定的位置,所以我可以从异常“Hash的奇数参数”中出来
提前谢谢
答案 0 :(得分:3)
arr = ["a", "apple", "b", "banyan", "banana", "c", "cat"]
indexes = [3, 4] # Define which two elements to merge.
arr[indexes[0]] += arr.delete_at(indexes[1])
arr # => ["a", "apple", "b", "banyanbanana", "c", "cat"]
答案 1 :(得分:1)
所以,对于一个值:
arr = ["a", "apple", "b", "banyan", "banana", "c", "cat"]
index = 3 # you can write `index = arr.find_index("banana")`
arr[index..(index+1)] = arr[index] + arr[index+1]
您可以使用官方ruby文档来了解哪些方法类支持:http://ruby-doc.org/core-2.0/Array.html