0

これが私のSinatraコードです

  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

このメソッドを#として呼び出すと、次sort_by_date_or_price(items, :date, :desc)のエラーが返されます。 NoMethodError: undefined method '-@' for 2013-02-05 02:43:48 +0200:Time

これを修正するにはどうすればよいですか?

4

2 に答える 2

1
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>'

以下でどのように修正したかを見てください。

class Person
  def -@
   p "-#{self}"
  end
end
#=> nil
ram = Person.new()
#=> #<Person:0x1f46628>
-ram
#=>"-#<Person:0x1f46628>"
=> "-#<Person:0x1f46628>"
于 2013-03-17T13:41:26.363 に答える
1

問題は、によって使用されるクラスTimeunary -で演算子が定義されていないことです。整数に変換する必要があります:created_date

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

それも書ける

items.sort_by{|x| x.created_date.to_i * (sort_direction == :asc ? 1 : -1)}
于 2013-03-17T14:03:31.267 に答える