---
title: "我也来出道rubyquiz：each_component"
author: "cvu"
date: "2008-03-27T15:09:46Z"
tags: []
slug: "rubyquiz-each-component"
draft: false
lastmod: "2008-03-27T15:09:46Z"
id: 176780
url: "https://cvu.iteye.com/blog/176780"
---

工作中碰到这样的问题，需要处理乘法法则排列组合后的每一种组合。具体说就是：用Hash表示一套组合，通过each_component把其中的每一种可能的组合抽出来，作为一个新的Hash，在block中使用。

改编成一个rubyquiz。要求：扩展Hash类，写一个each_component方法，让下面的代码可以运行出期望的结果来。

```ruby

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.

```


过几天贴出我的解法。