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)