【问题标题】:Ruby ArgumentError in Each Method每个方法中的 Ruby ArgumentError
【发布时间】:2015-03-21 13:51:14
【问题描述】:

Ruby 新手在这里学习全栈在线程序 Bloc 中的 each 方法和循环。这个具体问题已在before here 中讨论过,但我收到的错误消息与该帖子不同,我不知道为什么。

在说明中,class StringModifier“在初始化时获取一个字符串”和实例方法proclaim“将字符串拆分为一个单独的单词数组,为每个单词添加一个感叹号,然后用空格和返回新字符串。”

我在 irb 中不断收到错误 ArgumentError wrong number of arguments (0 for 1)。我不确定我在哪里声明一个论点。这不是初始化string 变量的目的吗?这是我关于 SO 的第一个问题,所以任何帮助或指向正确方向的人都将不胜感激。下面的代码和规范脚本:

class StringModifier
  attr_accessor :string

  def initialize(string)
    @string = string
  end

  def proclaim(string)
    new_array = []
    string.each do |x|
      new_array << "#{x.split(' ').join('!')}"
    end
    new_array
  end
end

这是规范脚本:

describe StringModifier do
  describe "#proclaim" do
    it "adds an exclamation mark after each word" do
      blitzkrieg_bop = StringModifier.new("Hey ho let's go").proclaim
      expect(blitzkrieg_bop).to eq("Hey! ho! let's! go!")
    end
  end

【问题讨论】:

    标签: ruby loops instance-methods argument-error


    【解决方案1】:

    您的proclaim 方法需要再次传入该字符串。这不是必需的,因为您已经在初始化时存储了字符串。您的代码似乎也包含一些问题,可以简化。试试这个:

    class StringModifier
      attr_accessor :string
    
      def initialize(string)
        @string = string
      end
    
      def proclaim
        @string.split(' ').join('! ').concat('!')
      end
    end
    

    【讨论】:

    • 感谢@Drenmi,澄清不需要再次传递字符串。错误消息现在停止,但字符串中的最后一个单词没有感叹号。结果不是"Hey! ho! let's! go!",而是"Hey! ho! let's! go"。字符串插值会解决这个问题,还是在字符串上运行each 方法?
    • @Jay:您可以使用.concat 在字符串末尾添加一个额外的感叹号:@string.split(' ').join('! ').concat('!') 我已更新答案以反映这一点。
    【解决方案2】:

    这对我有用。我自己正在学习 Bloc Ruby 课程。

    class StringModifier
      attr_accessor :string
    
      def initialize(string)
        @string = string
      end
    
      def proclaim
        new_array = []
        string.split.each do |word|
          new_array << "#{word}!"
        end
        new_array.join(" ")
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-07
      • 2013-04-28
      • 2023-01-17
      • 2012-03-18
      • 2014-10-20
      • 2015-10-06
      相关资源
      最近更新 更多