From: Peter Vandenabeele Date: 2011-12-10T21:22:04+09:00 Subject: Re: Ruby module error --bcaec5430516e647f004b3bbf2e2 Content-Type: text/plain; charset=UTF-8 On Sat, Dec 10, 2011 at 12:39 PM, Vadim Pirogov wrote: > How in ruby i can write module ? > so we have: > a=-4 > b=-9 > > g = Math.sqrt(Math.Module(a))*(Math.Module(b)) > def g(a, b) > Math.sqrt(Math.Module(a))*(Math.Module(b)) > end > > end when i write "puts g" i have a error. I try write Math.mod but > nothing. > "rb:4: undefined method `Module' for Math:Module (NoMethodError)" > For the module Math, you can easily see the documented instance and class methods with $ ri Math The term "Module" is not one of them, so that is why you get the error: "undefined method `Module' for Math:Module (NoMethodError)" You can use the module methods with Math.sin(0.75) You can use the instance methods with include Math sin(0.75) Regarding your question how to write a module, as example, I have written an Average module: peterv@ASUS:~$ cat average.rb module Average def geometric(*a) case a.size when 0 raise "At least one argument required" when 1 a[0] when 2 Math.sqrt(a[0]*a[1]) else (a.inject(1){|acc,e| acc*e})**(1.0/a.size) end end def arithmetic(*a) case a.size when 0 raise "At least one argument required" when 1 a[0] else (a.inject(0){|acc,e| acc+e})/Float(a.size) # force a float end end end and when I 'include' that, I can use the methods as instance methods (on main). An alternative would have been to define both methods as module methods (with "def self.geometric"). This would have the advantage of avoiding polluting the general name space with the "include Average" . peterv@ASUS:~$ irb 001:0> require 'average' => true 002:0> include Average => Object 003:0> geometric() RuntimeError: At least one argument required from ./average.rb:5:in `geometric' from (irb):3 004:0> geometric(4) => 4 005:0> geometric(4,9) => 6.0 006:0> geometric(4,9,48) => 12.0 007:0> arithmetic() RuntimeError: At least one argument required from ./average.rb:18:in `arithmetic' from (irb):7 008:0> arithmetic(7) => 7 009:0> arithmetic(4,7) => 5.5 010:0> arithmetic(4,7,6,9) => 6.5 In my "Average" module, I have now used the Math.sqrt module function of the Math module to demonstrate the proper use of such a module function. HTH, Peter --bcaec5430516e647f004b3bbf2e2--