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!
#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
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
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
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.