Ruby 中的“错误数量的参数(1 代表 0)”是什么意思?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7537450/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 04:21:00  来源:igfitidea点击:

What does "wrong number of arguments (1 for 0)" mean in Ruby?

ruby

提问by Kotaro Ezawa

What does "Argument Error: wrong number of arguments (1 for 0)" mean?

“参数错误:参数数量错误(1 代表 0)”是什么意思?

回答by bennett_an

When you define a function, you also define what info (arguments) that function needs to work. If it is designed to work without any additional info, and you pass it some, you are going to get that error.

当您定义一个函数时,您还定义了该函数需要工作的信息(参数)。如果它被设计为在没有任何附加信息的情况下工作,并且您传递了一些信息,您将收到该错误。

Example: Takes no arguments:

示例: 不带参数:

def dog
end

Takes arguments:

接受参数:

def cat(name)
end

When you call these, you need to call them with the arguments you defined.

当您调用这些时,您需要使用您定义的参数来调用它们。

dog                  #works fine
cat("Fluffy")        #works fine


dog("Fido")          #Returns ArgumentError (1 for 0)
cat                  #Returns ArgumentError (0 for 1)

Check out the Ruby Koansto learn all this.

查看Ruby Koans以了解所有这些。

回答by icktoofay

You passed an argument to a function which didn't take any. For example:

你将一个参数传递给一个没有接受任何参数的函数。例如:

def takes_no_arguments
end

takes_no_arguments 1
# ArgumentError: wrong number of arguments (1 for 0)

回答by Howard

I assume you called a function with an argument which was defined without taking any.

我假设您调用了一个带有参数的函数,该参数是在不带任何参数的情况下定义的。

def f()
  puts "hello world"
end

f(1)   # <= wrong number of arguments (1 for 0)

回答by justingordon

If you change from using a lambda with one argument to a function with one argument, you will get this error.

如果您从使用带一个参数的 lambda 更改为带一个参数的函数,您将收到此错误。

For example:

例如:

You had:

你有过:

foobar = lambda do |baz|
  puts baz
end

and you changed the definition to

并且您将定义更改为

def foobar(baz)
  puts baz
end

And you left your invocation as:

您将调用保留为:

foobar.call(baz)

And then you got the message

然后你收到了消息

ArgumentError: wrong number of arguments (0 for 1)

when you really meant:

当你真正的意思是:

foobar(baz)