我还是铁杆里的红宝石新手。今天我正在尝试编写一些可以执行以下操作的代码:
image = Image.new([
[0, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 0, 1],
[0, 0, 0, 0]
])
image.output_image
我无法设置初始化。我的代码如下,有人可以帮帮我吗? 非常感谢
class Subary
attr_accessor :num1, :num2, :num3, :num4
def initialize (num1, num2, num3, num4)
self.num1 = num1
self.num2 = num2
self.num3 = num3
self.num4 = num4
end
def output_subary
puts "#{num1}#{num2}#{num3}#{num4}"
end
end
# subary = Subary.new(0,0,0,0)
# puts subary.output_subary
class Image
def initialize
@subarys = []
@subarys << Subary.new(:num1, :num2, :num3, :num4)
@subarys << Subary.new(:num1, :num2, :num3, :num4)
@subarys << Subary.new(:num1, :num2, :num3, :num4)
@subarys << Subary.new(:num1, :num2, :num3, :num4)
end
def output_image
@subarys.each do |list|
list.output_subary
end
end
end
image = Image.new([
[0, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 0, 1],
[0, 0, 0, 0]
])
image.output_image
答案 0 :(得分:1)
`initialize': wrong number of arguments (1 for 0)
此错误表示initialize
方法不接受任何参数(0),但您向其传递了一个参数。更改initialize
课程中的Image
方法定义。然后,它应该工作。
class Subary
attr_accessor :num1, :num2, :num3, :num4
def initialize(sub_array)
self.num1 = sub_array[0]
self.num2 = sub_array[1]
self.num3 = sub_array[2]
self.num4 = sub_array[3]
end
def output_subary
puts "#{num1}#{num2}#{num3}#{num4}"
end
end
# subary = Subary.new(0,0,0,0)
# puts subary.output_subary
class Image
def initialize(array_of_arrays)
@subarys = []
@subarys << Subary.new(array_of_arrays[0])
@subarys << Subary.new(array_of_arrays[1])
@subarys << Subary.new(array_of_arrays[2])
@subarys << Subary.new(array_of_arrays[3])
end
def output_image
@subarys.each do |list|
list.output_subary
end
end
end
image = Image.new([
[0, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 0, 1],
[0, 0, 0, 0]
])
image.output_image
# => 0000
# => 0100
# => 0001
# => 0000