gpt4 book ai didi

ruby - 试图通过类和数组问题来理解一些东西

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

这里是 Ruby 新手。以下代码不起作用。

class Shows 
def echo
x, y, z = self
puts x
puts y
puts z
end
end

["Foo", 2, 2001].echo

确实如此。

class Array 
def echo
x, y, z = self
puts x
puts y
puts z
end
end

["Foo", 2, 2001].echo

我的理解是我可以通过

让 Shows 继承 Arrays
class Shows < Arrays

但这也行不通。

我知道我可以创建一个方法并像这样使用它

def echo(x, y, c)

puts x
puts y
puts z
end

然而,我想像在代码的第一部分那样做是有原因的。

最佳答案

在您的第一段代码中,您正在构建一个数组,然后在 Array 上未定义 echo 时尝试对其调用 #echo 。您更接近子类 Array 的想法,但您仍然必须实例化 Shows 实例,而不是 Array 实例!

你可以这样做:

# Create a new class called Shows, which is a subclass of Array
class Shows < Array
def echo
# In this case, since self is an Array subclass structure, you can use
# destructuring assignment to assign to x, y, and z
x, y, z = self
puts x
puts y
puts z
end
end

# Create a new Shows instance, passing in an array of values that should populate it.
# This works because Shows#initialize inherits from Array#initialize, which accepts an
# array as an input value.
Shows.new(["Foo", 2, 2001]).echo

关于ruby - 试图通过类和数组问题来理解一些东西,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26918014/

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