LoginSignup
16
14

More than 5 years have passed since last update.

ruby: wrong number of arguments

Last updated at Posted at 2014-04-15

rubyでプログラミングする際に,良く間違えるけど,どう間違ったのか分かりにくいエラー.

例えば,

class A
    attr_accessor :x

    def initialize(x)
        @x= x
    end 
end

のように,xという変数にアクセスできるクラスがある.
これにアクセスする次のようなプログラムを考える.

a= A.new(1.0)
b= (a.x +1.0)

これを実行しようとすると,おそらく,「wrong number of arguments (1 for 0)」となる.
これは,「a.x」が関数なので,その関数が「+1.0」という引数を取っていると判断されているからである.

a= A.new(1.0)
b= (a.x() +1.0)

このように,「a.x()」のように明示的に引数は0個だと書けば,上のような問題がなくなる.

しかしまぁ,関数呼び出しの書き方が複数あると便利なようだけど,分かりにくいエラーの原因となる.

16
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
14