gpt4 book ai didi

arrays - 在 Array 上定义一个 next_in_line 方法,该方法获取数组开头的元素并将其放在末尾

转载 作者:太空宇宙 更新时间:2023-11-03 17:14:55 24 4
gpt4 key购买 nike

这是我应该做什么的说明。

Define a next_in_line method on Array that takes the element at the beginning of the array and puts it at the end. Hint: remember, Array#shift removes the first element, and Array#push adds an element to the end.

我已经尝试了十几种变体,但似乎没有任何效果。这是我认为可行的方法:

class Array
define_method(:next_in_line) do
new_array = self.shift()
new_array = new_array.push()
end
end

请原谅我的非程序员语言语法,但这是我认为我在做的事情:

  1. 定义方法的类(数组)。
  2. 定义方法(下一行)
  3. 第三行删除数组的第一个元素
  4. 第四行将删除的元素推到最后。

然后我输入:["hi", "hello", "goodbye"].next_in_line()

这是我尝试时收到的错误消息:

NoMethodError: undefined method 'push' for "hi":String

为什么我的代码不起作用?

最佳答案

错误是因为:当不带参数调用时,self.shift 返回元素,而不是数组。

要修复错误,请使用:

class Array
def next_in_line
return self if empty?
push shift
end
end

["hi", "hello", "goodbye"].next_in_line
# => ["hello", "goodbye", "hi"]

请注意,有一个内置的 Array#rotate .

关于arrays - 在 Array 上定义一个 next_in_line 方法,该方法获取数组开头的元素并将其放在末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31530466/

24 4 0