Skip to content

Instantly share code, notes, and snippets.

@kaochenlong
Last active July 6, 2016 02:01
Show Gist options
  • Save kaochenlong/40da39697fa41528e629fb51d522f216 to your computer and use it in GitHub Desktop.
Save kaochenlong/40da39697fa41528e629fb51d522f216 to your computer and use it in GitHub Desktop.
class Product
# 實作
end
class Cart
# 實作
end
p1 = Product.new("ruby", 100)
p2 = Product.new("php", 200)
p3 = Product.new("javascript", 300)
p4 = Product.new("perl", 400)
p5 = Product.new("python", 600)
cart = Cart.new
cart.add_item(p1)
cart.add_item(p2)
cart.add_item(p3)
cart.add_item(p4)
cart.add_item(p5)
list = cart.select { |item| item.price <= 300 }
puts list
# 得到結果
# title: ruby, price: $100
# title: php, price: $200
# title: javascript, price: $300
@kaochenlong
Copy link
Author

class Product
  attr_reader :price, :title

  def initialize(title, price)
    @title = title
    @price = price
  end

  def to_s
    "title: #{title}, price: $#{price}"
  end
end

class Cart
  def initialize
    @items = []
  end

  def add_item(item)
    @items << item
  end

  def select
    @items.select { |item| yield item }
  end
end

p1 = Product.new("ruby", 100)
p2 = Product.new("php", 200)
p3 = Product.new("javascript", 300)
p4 = Product.new("perl", 400)
p5 = Product.new("python", 600)

cart = Cart.new
cart.add_item(p1)
cart.add_item(p2)
cart.add_item(p3)
cart.add_item(p4)
cart.add_item(p5)

list = cart.select { |item| item.price <= 300 }
list.each do |x|
  puts x
end

# 得到結果
# title: ruby, price: $100
# title: php, price: $200
# title: javascript, price: $300

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment