2009-12-24 79 views
0

語言:紅寶石在Ruby中排序陣列

我有一個產品陣列。每個產品都有一個稱爲product_price_name的屬性。

[Product.product_price_name =「所有價格」,Product.product_price_name =「$ 1到$ 100」]

我想這樣的第一個結果是「所有價格」,再下一個選項將是解決這陣價格範圍如$ 1- $ 100,$ 100- $ 200

+0

您已經對此有任何疑問(您已經接受了答案)。請不要以這種方式傳播一個問題。 – Telemachus 2009-12-24 16:48:44

回答

4
# 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。

+0

我從來沒有見過這種方法,我不是一個非常棒的程序員。你可以給我一個副本和過去的代碼放在這個數組[Product.product_price_name =「All Prices」,Product.product_price_name =「$ 1到$ 100」]。 – s84 2009-12-24 14:46:45

+0

oops,錯誤的語法,我的壞。它是'array.sort_by',而不是'array sort_by:'(今天編寫了太多的Pharo)。 – akuhn 2009-12-24 16:49:42

+0

它現在更加錯了。 – akuhn 2009-12-24 17:06:37