Search code examples
rubyloopsinstance-methodsargument-error

Ruby ArgumentError in Each Method


Ruby Newbie here learning about each methods and loops in the full stack online program Bloc. This specific problem has been talked about before here, but I'm getting a different error message than that post and I'm not sure why.

In the instructions, the class StringModifier "takes a string on initiation" and instance method proclaim "splits the string into an array of separate words, adds an exclamation mark to each, then joins them back together with spaces and returns the new string."

I keep receiving an error an ArgumentError wrong number of arguments (0 for 1) in the irb. I'm not sure where I'm not declaring an argument. Isn't that what initializing the string variable is for? This is my first question on SO, so any help or point in the right direction would be appreciated. Code and spec script below:

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

Here is the spec script:

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

Solution

  • Your proclaim method expects the string to be passed in again. This is not needed, since you already store the string on initialization. It also seems your code contained some issues and can be simplified. Try this:

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