変数の扱いで悩んだ→解決
hash = Hash.new hash["0"] = 0 hash["1"] = 1 hash["2"] = 1 def fib(n) if hash["#{n}"] then return hash["#{n}"] end f = fib(n-1) + fib(n-2) hash["#{f}"] = f f end (0..40).each do |n| puts "F_{#{n}} = #{fib(n)}" end
↑のプログラムを動かそうとすると、↓のようなエラーになります。
a.rb:7:in `[]': can't convert String into Integer (TypeError) from a.rb:7:in `fib' from a.rb:14 from a.rb:13
エラーメッセージにすごく悩む。
実は外の(トップレベルの?)hashとfibメソッド内のhashが別物なのかな?
↓で調べてみる。.classを使って「あなたは何年何組どのクラスのひと?」と聞いてみる。
hash = Hash.new hash["0"] = 0 hash["1"] = 1 hash["2"] = 1 p hash.class #=> Hash def fib(n) p hash.class #=> Fixnum if hash["#{n}"] then return hash["#{n}"] end f = fib(n-1) + fib(n-2) hash["#{f}"] = f f end (0..40).each do |n| puts "F_{#{n}} = #{fib(n)}" end
Hash Fixnum a.rb:9:in `[]': can't convert String into Integer (TypeError) from a.rb:9:in `fib' from a.rb:16 from a.rb:15
がーん。Fixnumなんだって。どうしてでしょう。Rubyでは、代入されていないローカル変数はFixnumなんでしたっけ。そんなことないですよねえ。
def foo p hello.class end foo
これを動かすと、↓のようなエラーになる。あれー。
a.rb:2:in `foo': undefined local variable or method `hello' for main:Object (NameError) from a.rb:4
未解決。ちなみにバージョンは。
> ruby -v ruby 1.8.4 (2005-12-24) [i386-mswin32]
もしかして、hashという名前が駄目なの?
hash = Hash.new p hash.class #=> Hash def method p hash.class #=> Fixnum end method
がーん!どうしてどうして?
p hash.class #=> Fixnum
あれー?
追記:わかった!hash()だ!…と思ったらすでに ささださんからコメントをいただいていました。早っ!(ありがとうございます)