DEV Community

n350071πŸ‡―πŸ‡΅
n350071πŸ‡―πŸ‡΅

Posted on

Object Hash Pattern in Ruby

πŸ€” Situation

You have a class. You want to store objects of it.

class Card
  attr_accessor :name, :g, :last, :called

  def initialize(name)
    @name = name
  end
end

πŸ€” Array?

This is ok. But when you use it, you have to check what the element is.

@cards = []
[:paprika, :tomato, :cabage].each do |name|
  cards << Card.new(name)
end

πŸ¦„ Hash

I like this way.

@cards ={}
[:paprika, :tomato, :cabage].each do |name|
  cards[name]= Card.new(name)
end

You can get the object by the key of the object name.

def put(card_name)
  @cards[card_name].last = true
end

🀩 HELP

I don't know the real name of this pattern. If you know it, I'm happy if you leave a comment.


πŸ”— Parent Note

Top comments (0)