简体   繁体   中英

sorting an array of objects by attribute in ruby raises undefined method error

I'm new to the ruby world and I'm currently struggling with the following code:

class Item
  attr_accessor :x, :y
  def initialize(x,y)
    @x, @y = x, y
  end
  def to_s
    "(#@x,#@y)"
  end
end
a = Item.new(1,nil)
b = Item.new(2,nil)
c = Item.new(3,nil)
d = Item.new(4,nil)
e = Item.new(5,12)
f = Item.new(6,5)
g = Item.new(12,6)

ar = [ a, b, c, d, e, f,g]
ar.sort! {|i1,i2| (i2.y?i2.y:i2.x) <=> (i1.y?i1.y:i1.x)}
puts array.ar("\n")

This raises the following error in the sort line:

undefined method `x' for :i2:Symbol (NoMethodError)

Clearly, x is a method of instances of the Item class, so my guess is that i1 and i2 are not instances of the Item class - but if they are not, then what are they?

(Btw, what I'm trying to do here is to sort the array of objects according to attribute y, and if y is nil, according to attribute x instead).

Thanks for any help to a ruby-newby

You need some whitespaces. Any token starting with a : is a symbol in Ruby.

ar.sort! {|i1,i2| (i2.y ? i2.y : i2.x) <=> (i1.y ? i1.y : i1.x)}

And the last line, puts ar is ok.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM