多维数组-'initialize':错误的参数数量(1表示0) [英] Multidimestional Array - `initialize': wrong number of arguments (1 for 0)

查看:166
本文介绍了多维数组-'initialize':错误的参数数量(1表示0)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我还是红宝石领域的新手.今天,我正在尝试编写一些可以运行以下代码的代码:

I'm still new in ruby in rails. Today I'm trying to write some codes which can run the the following:

image = Image.new([
  [0, 0, 0, 0],
  [0, 1, 0, 0],
  [0, 0, 0, 1],
  [0, 0, 0, 0]
])

image.output_image

我在设置初始化时遇到了麻烦.我的代码如下,有人可以帮助我吗? 非常感谢

And I'm having trouble setup the initialize. My codes is as below, can someone help me? Thanks a lot

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

推荐答案

`initialize': wrong number of arguments (1 for 0)

此错误意味着,initialize方法不接受任何参数(0),但是您向其传递了一个参数.在您的Image类中更改initialize方法的定义.然后,它应该可以工作.

This error means that, initialize method does not take any argument (0), but you passed one argument to it. Change the initialize method's definition in your Image class. Then, it should work.

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

这篇关于多维数组-'initialize':错误的参数数量(1表示0)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆