2013-03-17 151 views
0

这里是我的末日代码NoMethodError:未定义的方法“ - @”

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 '[email protected]' for 2013-02-05 02:43:48 +0200:Time

如何解决这个错误?

+0

你需要写一元运算符'-'该方法。这是不存在的,因此从'-x.item.current_price'或'-x.created_date'行确定出错。 – 2013-03-17 13:37:19

+0

@iAmRubuuu,这段代码工作'items.sort_by {| x | -x.created_date}' – 2013-03-17 13:46:24

回答

1

的问题是,运营商unary -未通过created_date使用该类Time定义。你应该把它转换为整数:

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)} 
+0

如果'sort_direction!=:asc',我会在最后做一个'reverse'。 – 2013-03-18 18:18:03

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

现在看到我是如何修复它下面:

class Person 
    def [email protected] 
    p "-#{self}" 
    end 
end 
#=> nil 
ram = Person.new() 
#=> #<Person:0x1f46628> 
-ram 
#=>"-#<Person:0x1f46628>" 
=> "-#<Person:0x1f46628>" 
+0

再次阅读我的问题 – 2013-03-17 13:45:28

+0

@AlanDert你提到的错误只有当我提到的后场景出现时才会出现。尝试看看我在答案中提到的内容。 – 2013-03-17 13:46:51

+0

将工作排序? – 2013-03-17 13:52:03

相关问题