Ruby: Modules, Mixins, Fixins, and Rails (Page 1 of 4 )
Some time ago we discussed working with Ruby Objects and Classes. We are going to continue that discussion some more here, as we learn to work with Modules and Mixins. After that we will go over Rails and learn to create our first application with it.
Modules Ate My Homework
Working with a lot of classes can be overwhelming -- just ask any college professor. Seriously, to avoid confusion, I suggest you use modules to group those classes together. Modules also save programmers time, by giving them a shortcut. Rather than having to write a whole bunch of code over and over again, they can call the module with a few lines (if not just a line) over and over again. You can place the code that calls upon your modules and the actual modules themselves in the same file, or you can save them in separate files, as we will do below.
First, we will create our Addition.rb module:
module Addition
def Addition.add(operand_one, operand_two)
return operand_one + operand_two
end
end
Next we will create a module to perform multiplication named Multiply.rb:
module Multiply
def Multiply.add(multiple_one, multiple_two)
return multiple_one * multiple_two
end
end
And finally, we we will create another new file to call the two modules, named callmodules.rb:
require 'addition'
require 'multiply'
puts "My IQ plus your IQ =" + Addition.add(200, 10).to_s
puts "Of course my IQ is 200, so that means that yours is..."
puts "Imagine if we multiplied our IQs!"
puts "The result of that would be: " + Multiply.add(200, 10).to_s
The above results in the following being displayed:
MY IQ plus your IQ = 210
Of course my IQ is 200, so that means that yours is...
Imagine if we multiplied our IQs!
The result of that would be: 2000
The cool part of modules is that now that I have created my addition and multiply module, I can call them over and over again. Here is a sample:
require 'addition'
require 'multiply'
puts "My IQ plus your IQ =" + Addition.add(200, 10).to_s
puts "Of course my IQ is 200, so that means that yours is..."
puts "Imagine if we multiplied our IQS!"
puts "The result of that would be: " + Multiply.add(200, 10).to_s
puts " "
puts "Your weight plus my weight is: " + Addition.add(340, 100).to_s
puts "My weight times your weight is: " + Multiply.add(340, 100).to_s
Here we call on each module not once, but twice, giving the variables within each module a different value. Here is the result:
MY IQ plus your IQ = 210
Of course my IQ is 200, so that means that yours is...
Imagine if we multiplied our IQs!
The result of that would be: 2000
Your weight plus my weight is: 440
My weight times your weight is: 340,000
Next: A Few Notes >>
More Ruby-on-Rails Articles
More By James Payne