简体   繁体   中英

Ruby Is it possible to create directory for variables?

I am not sure how to put this question without it being wordy and confusing. I want to store a variable inside of another variable, and have those variables be specific to their home variable (basically creating a directory). Say I have three characters, Max, Sam, and Greg. I want to store how many treats each of these characters has.

So:

Max = [3 cookies, 4 donuts, 1 cakes]
Sam = [1 cookies, 5 donuts, 0 cakes]
Greg =[2 cookies, 4 donuts, 5 cakes]

And then later, I want to give or take away certain treats from a character, or ask how many of a certain kind of treat they have. How would I do this?

I want Max's cookies to be independent from Sam's cookies. However, I still want to be able to write a general method that can increase everyone's cookies.

 def givecookies 
  @cookies=(@cookies+1) 

But then I want to be able to call how many cookies Max has. So, is there a way I can store a variable inside another variable, and then how do I call it? Like, instead of puts cookies, could I do something like puts (Max/cookies)?

I'm sorry for the awkwardness of the question. I've only been programming a few weeks, and I am still trying to pick up on the basics. There is probably a method out there for it, but I don't know what to look for.

You shell use hash-like structures, like Hash itself, Struct , or Hashie -based classes. I'd prefer to use, for example, Hashie gem and Hashie::Mash class as follows:

@h = Hashie::Mash.new
# ...
@h.Max = Hashie::Mash.new
@h.Max.cookies = 3
@h.Max.donuts = 4
@h.Max.cakes = 1
@h
# => #<Hashie::Mash Max=#<Hashie::Mash cakes=1 cookies=3 donuts=4>>

def givecookies 
   @h.each {|_,y| y.cookies += 1}
end

Or with built-in Struct :

s = Struct.new( :cookies, :donuts, :cakes )
@s = { :Max => s.new( 3, 4, 1 ),
       :Sam => s.new( 1, 5, 0 ),
       :Greg => s.new( 2, 4, 5 ) }

def givecookies 
   @s.each {|_,y| y.cookies += 1}
end
class Person
  attr_accessor :name, :cookies
  def initialize name, cookies = 0
    @name = name
    @cookies = cookies
  end
end

p_max = Person.new 'Max', 3
puts "Max has #{p_max.cookies} cookies"
# ⇒ Max has 3 cookies
p_max.cookies += 2
puts "Max has #{p_max.cookies} cookies"
# ⇒ Max has 5 cookies

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM