DevHeads.net

Module using object defined outside of method?

I have a class Dice with a method "roll_1". It gives a result between 1-6.

###
class Dice
def roll_1
rand(1..6)
end
end
###

The module CharacterTools uses Dice.roll_1.

###
module CharacterTools

require 'dice'
dice = Dice.new

def roll_1
dice = Dice.new
dice.roll_1
end
end
###

"dice" is declared twice, outside and inside the roll_1 method
definition. I am trying to figure out how to instantiate one "dice"
object outside of the method that calls it. For each program run there
are lots of calls to roll_1. It seems better to create one Dice object
and call it a lot of times.

CharacterTools itself is mixed in with other classes.

This is a personal learning exercise so pointers to good tutorials are
better than outright answers. Even good Google search terms would be better.

Thanks!

Leam

Unsubscribe: <mailto:ruby-talk-request@ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-talk>

Comments

RE: Module using object defined outside of method?

By Andy Jones at 02/13/2018 - 07:13

###
module CharacterTools

require 'dice'
dice = Dice.new

def roll_1
dice = Dice.new
dice.roll_1
end
end
###

<<<<<<<<

The simple answer is that the first declaration of dice isn't doing anything. You can leave it out.

Since this is a mixin, you could always have it declare a @dice attribute that you can reuse later. That would look something like this:

###
require 'dice' # really this should be at the top of the file?

module CharacterTools

def dice
@dice ||= Dice.new
end

def roll_1
dice.roll_1
end

end
###

The dice method is a slightly sneaky trick: if @dice is already defined then it returns it; otherwise it defines it and returns it. So you can use dice exactly as if it was an automagically defined @dice attribute.

Hope that helps...

Click here to view Company Information and Confidentiality Notice.<http://www.jameshall.co.uk/index.php/small-print/email-disclaimer>

Unsubscribe: <mailto:ruby-talk-request@ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-talk>