Bird Count에서는 count, any?, select, all?, map 열거 메서드를 배웠어요.
여기서는 몇 가지를 더해 다시 정리해볼게요:
fibonacci = [0, 1, 1, 2, 3, 5, 8, 13]
fibonacci.count { |number| number == 1 } #=> 2
fibonacci.any? { |number| number > 20 } #=> false
fibonacci.none? { |number| number > 20 } #=> true
fibonacci.select { |number| number.odd? } #=> [1, 1, 3, 5, 13]
fibonacci.all? { |number| number < 20 } #=> true
fibonacci.map { |number| number * 2 } #=> [0, 2, 2, 4, 6, 10, 16, 26]
fibonacci.select { |number| number >= 5 } #=> [5, 8, 13]
fibonacci.find { |number| number >= 6 } #=> 8
# Some methods work with or without a block
fibonacci.sum #=> 33
fibonacci.sum { |number| number * number } #=> 273
# There are also methods to help with nested arrays:
animals = [ ['cat', 'bob'], ['horse', 'caris'], ['mouse', 'arya'] ]
animals.flatten #=> ["cat", "bob", "horse", "caris", "mouse", "arya"]
Hash 객체를 열거하는 방법은 Array 객체를 열거하는 것과 똑같아요.
다만 블록이 키와 값, 두 개의 인자를 받는다는 점만 달라요:
pet_names = {cat: "bob", horse: "caris", mouse: "arya"}
pet_names.each { |animal, name| ... }
값 둘 중 하나만 필요하다면, 필요하지 않은 값이 무엇인지 나타내는 특별한 _ 기호를 쓸 수 있어요.
이렇게 하면 코드를 읽는 사람이 더 명확하게 이해할 수 있고, 성능 최적화에도 도움이 돼요.
pet_names = {cat: "bob", horse: "caris", mouse: "arya"}
pet_names.map { |_, name| name } #=> ["bob", "caris", "arya"]
중첩된 블록 안에서 열거할 수도 있고, 메서드들을 연달아 이어 붙일 수도 있어요. 예를 들어 동물에 대한 해시들이 담긴 배열이 있고, 이름이 짧은 동물만 추려내고 싶다면 다음과 같이 하면 돼요:
pets = [
{ animal: "cats", names: ["bob", "fred", "sandra"] },
{ animal: "horses", names: ["caris", "black beard", "speedy"] },
{ animal: "mice", names: ["arya", "jerry"] }
]
pets.map { |pet|
pet[:names].select { |name| name.length <= 5 }
}.flatten.sort
#=> ["arya", "bob", "caris", "fred", "jerry"]
온라인 패션 부티크를 운영하고 있어요. 곧 큰 연간 세일이 다가오니, 재고를 파악해서 잘 준비되었는지 확인할 수 있는 기능을 만들어 보려고 해요.
재고의 아이템 하나는 해시로 표현하고, 전체 재고는 이런 해시들의 배열이에요.
[
{
name: "White Shirt",
price: 40,
quantity_by_size: {s: 3, m: 7, l: 8, xl: 4}
},
{ ... }
]
BoutiqueInventory.item_names를 구현하세요. 아이템 이름 목록을 알파벳순으로 정렬해서 반환해야 해요.
BoutiqueInventory.new([
{price: 65.00, name: "Maxi Brown Dress", quantity_by_size: {s: 3, m: 7, l: 8, xl: 4}},
{price: 50.00, name: "Red Short Skirt", quantity_by_size: {}},
{price: 29.99, name: "Black Short Skirt", quantity_by_size: {s: 1, xl: 4}},
{price: 20.00, name: "Bamboo Socks Cats", quantity_by_size: {s: 7, m: 2}}
]).item_names
#=> ["Bamboo Socks Cats", "Black Short Skirt", "Maxi Brown Dress", "Red Short Skirt"]
BoutiqueInventory.cheap을 구현하세요. 30달러보다 저렴한 아이템을 모두 반환해야 해요.
BoutiqueInventory.new([
{price: 65.00, name: "Maxi Brown Dress", quantity_by_size: {s: 3, m: 7, l: 8, xl: 4}},
{price: 50.00, name: "Red Short Skirt", quantity_by_size: {}},
{price: 29.99, name: "Black Short Skirt", quantity_by_size: {s: 1, xl: 4}},
{price: 20.00, name: "Bamboo Socks Cats", quantity_by_size: {s: 7, m: 2}}
]).cheap
# => [
# {price: 29.99, name: "Black Short Skirt", quantity_by_size: {s: 1, xl: 4}},
# {price: 20.00, name: "Bamboo Socks Cats", quantity_by_size: {s: 7, m: 2}}
# ]
BoutiqueInventory.out_of_stock을 구현하세요. 재고가 없는 아이템, 즉 quantity_by_size가 비어 있는 아이템을 모두 반환해야 해요.
BoutiqueInventory.new([
{price: 65.00, name: "Maxi Brown Dress", quantity_by_size: {s: 3, m: 7, l: 8, xl: 4}},
{price: 50.00, name: "Red Short Skirt", quantity_by_size: {}},
{price: 29.99, name: "Black Short Skirt", quantity_by_size: {s: 1, xl: 4}},
{price: 20.00, name: "Bamboo Socks Cats", quantity_by_size: {s: 7, m: 2}}
]).out_of_stock
#=> [{price: 50.00, name: "Red Short Skirt", quantity_by_size: {}}]
BoutiqueInventory.stock_for_item(name)을 구현해서 이름으로 아이템의 재고를 반환하세요.
BoutiqueInventory.new([
{price: 65.00, name: "Maxi Brown Dress", quantity_by_size: {s: 3, m: 7, l: 8, xl: 4}},
{price: 50.00, name: "Red Short Skirt", quantity_by_size: {}},
{price: 29.99, name: "Black Short Skirt", quantity_by_size: {s: 1, xl: 4}},
{price: 20.00, name: "Bamboo Socks Cats", quantity_by_size: {s: 7, m: 2}}
]).stock_for_item("Black Short Skirt")
#=> {s: 1, xl: 4}
BoutiqueInventory.total_stock을 구현해서 창고에 있는 아이템의 총수량을 계산하세요.
BoutiqueInventory.new([
{price: 65.00, name: "Maxi Brown Dress", quantity_by_size: {s: 3, m: 7, l: 8, xl: 4}},
{price: 50.00, name: "Red Short Skirt", quantity_by_size: {}},
{price: 29.99, name: "Black Short Skirt", quantity_by_size: {s: 1, xl: 4}},
{price: 20.00, name: "Bamboo Socks Cats", quantity_by_size: {s: 7, m: 2}}
]).total_stock
#=> 36
Exercism에 가입하고 Ruby 트랙을 개념 21개연습 문제 121개, 그리고 실제 사람의 멘토링과 함께 배우고 익혀 보세요. 모두 무료예요.