Question

Here is my Sinatra code

  def self.sort_by_date_or_price(items, sort_by, sort_direction)
    if sort_by == :price
      items.sort_by{|x| sort_direction == :asc ? x.item.current_price : -x.item.current_price}
    elsif sort_by == :date
      items.sort_by{|x| sort_direction == :asc ? x.created_date : -x.created_date}
    end
  end

when I call this method as #sort_by_date_or_price(items, :date, :desc) it returns the error of NoMethodError: undefined method '-@' for 2013-02-05 02:43:48 +0200:Time

How do I fix this?

Was it helpful?

Solution

The problem is that the unary - operator in not defined in the class Time used by created_date. You should convert it to an integer :

items.sort_by{|x| sort_direction == :asc ? x.created_date.to_i : -x.created_date.to_i}

That could also be written

items.sort_by{|x| x.created_date.to_i * (sort_direction == :asc ? 1 : -1)}

OTHER TIPS

class Person
end
#=> nil
ram = Person.new()
#=> #<Person:0x2103888>
-ram
NoMethodError: undefined method `-@' for #<Person:0x2103888>
        from (irb):4
        from C:/Ruby200/bin/irb:12:in `<main>'

Now see how I fixed it below:

class Person
  def -@
   p "-#{self}"
  end
end
#=> nil
ram = Person.new()
#=> #<Person:0x1f46628>
-ram
#=>"-#<Person:0x1f46628>"
=> "-#<Person:0x1f46628>"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top