Iterating over hashes to create instance variables

I’m working on a dice rolling program. Right now I’m storing user’s
choices in a hash labeled ‘dice_hash’. A user who has completed their
choices has effectively created a hash that looks like the following:

dice_hash{
“four” => 2
“six” => 5
“twenty” => 1
}

The key is the type of die, and the value is the number of dice selected
by the user. What I would like to do is create instance variable of the
type of die. While I know the following code to be incorrect, I think it
helps to explain what I’m trying to accomplish:

dice_hash.each_pair do |k, v|
@"#{k}"_sided_die = v #This line creates the instance variable
end

As always, any help would be greatly appreciated. Thanks!

~Mike V.

On 26/09/13 07:15, Mike V. wrote:

The key is the type of die, and the value is the number of dice selected
~Mike V.

This might be helpful for you =]

Sam

Hi Mike. Perhaps you can take this aproach:

class Dice

@dices = []

#so you can keep track of them
def self.dices
@dices
end

def initialize(sides, selected_dice)
@sides = sides #: String
@selected_dice = selected_dice #: Fixnum
#here the receiver of class() is self, so I’m talking to Dice
class.dices.<<(self)
end
end

#…whatever

dice_hash.each_pair do |k, v|
Dice.new(k, v) #This line creates the instance variable
end

See you around. :slight_smile:

Am 25.09.2013 21:15, schrieb Mike V.:

The key is the type of die, and the value is the number of dice selected
by the user. What I would like to do is create instance variable of the
type of die. While I know the following code to be incorrect, I think it
helps to explain what I’m trying to accomplish:

dice_hash.each_pair do |k, v|
@"#{k}"_sided_die = v #This line creates the instance variable
end

You are better off simply using the hash itself.

Regards,
Marcus

Am 26.09.2013 18:55, schrieb [email protected]:

You are better off simply using the hash itself.

Well, seems Robert already told you the same :slight_smile:

Regards,
Marcus

On Wed, Sep 25, 2013 at 9:15 PM, Mike V. [email protected]
wrote:

The key is the type of die, and the value is the number of dice selected
by the user. What I would like to do is create instance variable of the
type of die. While I know the following code to be incorrect, I think it
helps to explain what I’m trying to accomplish:

dice_hash.each_pair do |k, v|
@“#{k}”_sided_die = v #This line creates the instance variable
end

As always, any help would be greatly appreciated. Thanks!

You won’t gain much by doing this because you then also would need to
generate code which accesses these instance variables. In these cases
one is usually better off by just storing the Hash (or a copy of it if
you are afraid of aliasing effects).

Kind regards

robert