Pebble Coding

ソフトウェアエンジニアによるIT技術、数学の備忘録

ruby文法その3

前回のソースコードをもう少し見ていきます。 少し変更して次のようにしてみるとどうなるでしょうか?

# MyMathModule.rb
module MyMathModule
  def plus(x, y)
    x + y + (@something || 0)
  end
end
# MyApp.rb
require './MyMathModule'

class MyApp
  include MyMathModule
end

myapp = MyApp.new
p myapp.plus(1,2)
~/ruby_test$ ruby MyApp.rb 
3

エラーになりませんでした。Mixinされるクラスにそのクラス変数が存在しなくてもよいようです。 ちなみに

# MyMathModule.rb
module MyMathModule
  def plus(x, y)
    x + y + @something
  end
end

のようにnil判定を入れないと、以下のようにエラーになりますのでご注意を。

~/ruby_test$ ruby MyApp.rb 
/Users/pebble8888/ruby_test/MyMathModule.rb:4:in `+': nil can't be coerced into Fixnum (TypeError)
    from /Users/pebble8888/ruby_test/MyMathModule.rb:4:in `plus'
    from MyApp.rb:9:in `<main>'