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)