gpt4 book ai didi

arrays - 将项目添加到具有索引的新数组

转载 作者:太空宇宙 更新时间:2023-11-03 16:22:53 25 4
gpt4 key购买 nike

尝试创建一个方法 skip_animals,它接受一个 animals 数组和一个 skip 整数,并返回除第一个 之外的所有元素的数组>跳过 个项目。

输入:skip_animals(['豹', '熊', '狐狸', '狼'], 2)

预期输出:["2:fox", "3:wolf"]

   def skip_animals(animals, skip)
arr = Array.new
animals.each_with_index{|animal, index| arr.push("#{animal}:#{index}") }
puts arr.drop(skip)
end

这反而每个输出放在单独的一行上,并且不会将它们添加到数组arr。我认为 arr.push 会正确添加它们。我需要做什么才能将元素添加到数组中?

我想使用这些方法,而不是 map 或更高级的方法。我需要修改此 each_with_index 行,而不是彻底修改它。

(这是Hackerrank上的挑战,所以使用了STDIN和STDOUT)

编辑

这是我使用 p 而不是 puts 的更新代码。它给了我两个不同数组的奇怪输出,不知道为什么。

def skip_animals(animals, skip)
arr = Array.new
animals.each_with_index{|animal, index| arr.push("#{index}:#{animal}") }
p arr.drop(skip)
end

这给了我两行输出:

["3:panda", "4:tiger", "5:deer"]
["0:leopard", "1:bear", "2:fox", "3:wolf", "4:dog", "5:cat"]

我假设顶部是正确的数组,但我不明白为什么第二个也在打印,或者为什么它有一组不同的动物。

最佳答案

使用p而不是 puts .

irb(main):001:0> puts ['1', '2']
1
2
=> nil
irb(main):002:0> p ['1', '2']
["1", "2"]

根据 the documentation , 放置:

Writes the given objects to ios as with IO#print. Writes a record separator (typically a newline) after any that do not already end with a newline sequence. If called with an array argument, writes each element on a new line. If called without arguments, outputs a single record separator.


顺便说一句,我会这样编码(使用 Enumerable#map + 返回结果而不是在函数内部打印):

def skip_animals(animals, skip)
animals.drop(skip).each_with_index.map { |animal, index|
("#{index + skip}:#{animal}")
}
end

p skip_animals(['leopard', 'bear', 'fox', 'wolf'], 2)

关于arrays - 将项目添加到具有索引的新数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31065022/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com