0

Language: Ruby

I have an array of Products. Each Product has an attribute called product_price_name.

[Product.product_price_name = "All Prices", Product.product_price_name = "$1 to $100" ]

I want to sort this array so the first result is "All Prices" and then the next options will be price ranges such as $1- $100, $100- $200

1
  • You already have a question for this (where you already accepted an answer). Please don't spread one question out this way. Commented Dec 24, 2009 at 16:48

1 Answer 1

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">]

Gosh, one should never submit code that had never run! Mea culpa.

Sign up to request clarification or add additional context in comments.

2 Comments

I have never seen this method before and I'm not a really great programmer. Can you please give me a copy and past code to put on this array [Product.product_price_name = "All Prices", Product.product_price_name = "$1 to $100" ].
oops, wrong syntax, my bad. It is array.sort_by and not array sort_by: (programming too much Pharo today).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.