Rails用Struct代替Hash

分類:IT技術 時間:2016-10-16
#有時候經常要自定義一些hash列表。
hash = {:matched=>[{:lidx=>"lidx1",:cont=>"cont1"},{:lidx=>"lidx2",:cont=>"cont2"}]}
hash[:matched].each do |ma|
  p ma[:lidx]
  p ma[:cont]
end 

#用Struct代替Hash
GrepMatchedItem = Struct.new(:lidx, :cont)
matched = []
matched << GrepMatchedItem.new(lidx, line)

matched.each do |m|
  p m.lidx
  p m.cont
end

#Struct的好處還可以像類一樣給他定義一些方法
Customer = Struct.new(:name, :address) do
  def greeting
    "Hello #{name}!"
  end
end
Customer.new("Dave", "123 Main").greeting  # => "Hello Dave!"

Tags: address

文章來源:


ads
ads

相關文章
ads

相關文章

ad