简单的红宝石问题。假设我有一个包含10个字符串的数组,我想将数组[3]和数组[5]中的元素移动到一个全新的数组中。然后,新数组将只有我从第一个数组移动的两个元素,然后第一个数组将只有8个元素,因为其中两个元素已被移出。
答案 0 :(得分:4)
使用Array#slice!
从第一个数组中删除元素,然后使用Array#<<
将它们附加到第二个数组:
arr1 = ['Foo', 'Bar', 'Baz', 'Qux']
arr2 = []
arr2 << arr1.slice!(1)
arr2 << arr1.slice!(2)
puts arr1.inspect
puts arr2.inspect
输出:
["Foo", "Baz"]
["Bar", "Qux"]
根据您的具体情况,您可能会发现数组上的其他方法更有用,例如Enumerable#partition
:
arr = ['Foo', 'Bar', 'Baz', 'Qux']
starts_with_b, does_not_start_with_b = arr.partition{|word| word[0] == 'B'}
puts starts_with_b.inspect
puts does_not_start_with_b.inspect
输出:
["Bar", "Baz"]
["Foo", "Qux"]
答案 1 :(得分:2)
a = (0..9).map { |i| "el##{i}" }
x = [3, 5].sort_by { |i| -i }.map { |i| a.delete_at(i) }
puts x.inspect
# => ["el#5", "el#3"]
puts a.inspect
# => ["el#0", "el#1", "el#2", "el#4", "el#6", "el#7", "el#8", "el#9"]
正如评论中所指出的那样,使指数保持原状有一些魔力。首先使用a.values_at(*indices)
获取所有需要的元素,然后将其删除,就可以避免这种情况。
答案 2 :(得分:2)
<强>代码:强>
arr = ["null","one","two","three","four","five","six","seven","eight","nine"]
p "Array: #{arr}"
third_el = arr.delete_at(3)
fifth_el = arr.delete_at(4)
first_arr = arr
p "First array: #{first_arr}"
concat_el = third_el + "," + fifth_el
second_arr = concat_el.split(",")
p "Second array: #{second_arr}"
<强>输出:强>
c:\temp>C:\case.rb
"Array: [\"null\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"s
even\", \"eight\", \"nine\"]"
"First array: [\"null\", \"one\", \"two\", \"four\", \"six\", \"seven\", \"eight
\", \"nine\"]"
"Second array: [\"three\", \"five\"]"
答案 3 :(得分:0)
以这种方式:
vals = arr.values_at *pulls
arr = arr.values_at *([*(0...arr.size)] - pulls)
试试吧。
arr = %w[Now is the time for all Rubyists to code]
pulls = [3,5]
vals = arr.values_at *pulls
#=> ["time", "all"]
arr = arr.values_at *([*(0...arr.size)] - pulls)
#=> ["Now", "is", "the", "for", "Rubyists", "to", "code"]
arr = %w[Now is the time for all Rubyists to code]
pulls = [5,3]
vals = arr.values_at *pulls
#=> ["all", "time"]
arr = arr.values_at *([*(0...arr.size)] - pulls)
#=> ["Now", "is", "the", "for", "Rubyists", "to", "code"]
答案 4 :(得分:0)
为什么不从最高索引开始删除。
arr = ['Foo', 'Bar', 'Baz', 'Qux']
index_array = [2, 1]
new_ary = index_array.map { |index| arr.delete_at(index) }
new_ary # => ["Baz", "Bar"]
arr # => ["Foo", "Qux"]