0

I know this question may seem very specific, but I'm trying to update some scripts to run on ruby 1.9 and have run into this very similar error on more than one occasion. I'm trying to run this code here: http://x.gfax.ch/Archives/Scripts/boggle.rb but get stuck in:

def Dict.to_n(ch)
    ch[0]-'a'[0]
end

In ruby1.8, this generates a random NxN boggle board then finds and outputs all the words it can find in it. In ruby1.9, however, the interpreter gives me this message:

boggle.rb:182:in `to_n': undefined method `-' for "a":String (NoMethodError)

What's wrong with my syntax? (If you need a dictionary file to play with the script, I'm using the one given at the bottom of this example page: http://learnruby.com/boggle/index.shtml) Thank you ahead of time for any guidance.

  • `ch[0]` is returning the String "a" which doesn't have a `-` method. Can you clarify what you're passing into this method and what you expect to happen, exactly? – rfunduk May 23 '12 at 21:32

2 Answers2

1

In Ruby 1.9, the method String#[] returns a string, while in Ruby 1.8 it returns a numerical value. (cf. here) You might consider using String#chars instead.

jtbandes
  • 115,675
  • 35
  • 233
  • 266
  • `chars` still returns an array of Strings of length one, [`codepoints`](http://ruby-doc.org/core-1.9.3/String.html#method-i-codepoints) is probably the right thing. – Andrew Marshall May 23 '12 at 22:08
0

You may want to try something like this:

  def Dict.to_n(ch)
    if ch.respond_to? :codepoints #1.9+
      ch.codepoints.first - 'a'.codepoints.first
    else
      ch[0]-'a'[0]
    end
  end
Mark Thomas
  • 37,131
  • 11
  • 74
  • 101
  • Thank you so much! I didn't know how else to pass the characters. Now to replace all the arrays.to_s's with .join's to fix the output :P – rubyuser1357796 May 24 '12 at 02:42