繁体   English   中英

ArgumentError:参数数量错误(给定 0,预期为 1) - Ruby

[英]ArgumentError: wrong number of arguments (given 0, expected 1) - Ruby

我有一个测试套件(hello_world_test.rb),它具有以下内容

#!/usr/bin/env ruby
begin
  gem 'minitest', '>= 5.0.0'
  require 'minitest/autorun'
  require_relative 'hello_world'
rescue Gem::LoadError => e
  puts "\nMissing Dependency:\n#{e.backtrace.first} #{e.message}"
  puts 'Minitest 5.0 gem must be installed for the xRuby track.'
rescue LoadError => e
  puts "\nError:\n#{e.backtrace.first} #{e.message}"
  puts DATA.read
  exit 1
end

# Test data version:
# deb225e Implement canonical dataset for scrabble-score problem (#255)

class HelloWorldTest < Minitest::Test
  def test_no_name
    assert_equal 'Hello, World!', HelloWorld.hello()
  end

  def test_sample_name 
    assert_equal 'Hello, Alice!', HelloWorld.hello('Alice')
  end

  def test_other_sample_name
    assert_equal 'Hello, Bob!', HelloWorld.hello('Bob')
  end
end

__END__

在此基础上,我实现了如下代码

class HelloWorld
    def self.hello
        "Hello, World!"
    end

    def self.hello(named)
        "Hello, #{named}!"
    end
end

现在我的两个测试用例正在通过,第一个测试用例正在返回

ArgumentError:参数数量错误(给定 0,预期为 1)/Users/vijay/Codes/Ruby/ruby/hello-world/hello_world.rb:7:in hello' hello_world_test.rb:21:in test_no_name'

一些机构可以帮助我吗?

Ruby 中没有通过 params 重载的方法。 用你对hello的第二个定义覆盖了第一个定义。 无论如何,您只需使用一种具有参数默认值的方法即可获得相同的行为。

def self.hello(named = 'World')
  "Hello, #{named}!"
end

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM