語言:紅寶石在Ruby中排序陣列
我有一個產品陣列。每個產品都有一個稱爲product_price_name的屬性。
[Product.product_price_name =「所有價格」,Product.product_price_name =「$ 1到$ 100」]
我想這樣的第一個結果是「所有價格」,再下一個選項將是解決這陣價格範圍如$ 1- $ 100,$ 100- $ 200
語言:紅寶石在Ruby中排序陣列
我有一個產品陣列。每個產品都有一個稱爲product_price_name的屬性。
[Product.product_price_name =「所有價格」,Product.product_price_name =「$ 1到$ 100」]
我想這樣的第一個結果是「所有價格」,再下一個選項將是解決這陣價格範圍如$ 1- $ 100,$ 100- $ 200
# some setup
Product = Struct.new(:product_price_name)
array = %w{$1-100 $200-1000 All_Prices $100-200}.collect{|each|Product.new(each)}
# the actual code
array = array.sort_by { |each| each.product_price_name }
array.unshift array.pop
array # => [#<struct Product product_price_name="All_Prices">, #<struct Product product_price_name="$1-100">, #<struct Product product_price_name="$100-200">, #<struct Product product_price_name="$200-1000">]
天哪,永遠不應該提交從未運行的代碼! Mea culpa。
您已經對此有任何疑問(您已經接受了答案)。請不要以這種方式傳播一個問題。 – Telemachus 2009-12-24 16:48:44