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
文章來源: