我也来出道rubyquiz:each_component

工作中碰到这样的问题,需要处理乘法法则排列组合后的每一种组合。具体说就是:用Hash表示一套组合,通过each_component把其中的每一种可能的组合抽出来,作为一个新的Hash,在block中使用。

改编成一个rubyquiz。要求:扩展Hash类,写一个each_component方法,让下面的代码可以运行出期望的结果来。
class Sneaker
  def initialize(attributes)
    @brand, @size, @store = attributes[:brand], attributes[:size], attributes[:store]
  end

  def to_s
    "#{@brand} sneakers of #{@size}in from #{@store} store."
  end
end

sneaker_combination = {
  :brand => [:adidas, :nike], 
  :size => [38, 40, 42], 
  :store => :shanghai
}

sneaker_combination.each_component do |sneaker|
  # sneaker_sample.should.be({:brand => :nike, :size => 38, :store => :shanghai})
  puts Sneaker.new(sneaker)
end
# should print:
# adidas sneakers of 38in from shanghai store.
# adidas sneakers of 40in from shanghai store.
# adidas sneakers of 42in from shanghai store.
# nike sneakers of 38in from shanghai store.
# nike sneakers of 40in from shanghai store.
# nike sneakers of 42in from shanghai store.


过几天贴出我的解法。

你可能感兴趣的:(C++,c,算法,C#,Ruby)