Search code examples
ruby-on-railsrubymethodsundefinednomethoderror

Ruby: NoMethodError without naming the undefined method?


I'm trying to implement my first program in Ruby but I keep getting a no method error:

undefined method ` ' for MyString:Class (NoMethodError) from assignment.rb:1:in `<main>

I can't work out why or find anything online to help me solve this. I'm sure its something simple I've missed but would really appreciate help on this, thank you. My code is below.

class MyString

  def initialize(txt1 = "Hello, World!")
    @str = txt1
    @letters = Hash.new
  end

  def str
    @str
  end

  def letters
    @letters
  end

  def frequency
    @str.downcase.each_char.with_object({}) { |c,h|
        (h[c] = h.fetch(c,0) + 1) if c =~ /[a-z]/ }
  end

  def histogram
    @str.downcase!
    freqs = {}
    freqs.default = ''
    @str.each_char { |char| freqs[char] += '*'}
    ("a".."z").each {|x| puts "#{x} : #{freqs[x]}" }
  end

end

Solution

  • Check your file for some invisible whitespace that is not a regular space . Usually the same thing happens to me on a Mac with a german keyboard (I think on some modifier key + Space). The easiest thing is to open all the files in an editor in the terminal like vim or just cat them, since the special chars are often displayed there (as some strange unicode sequence).