-1
class Song
  include Comparable
  attr_accessor :song_name
  def <=>(other)
    @song_name.length <=> other.length
  end

  def initialize(song_name)
    @song_name = song_name
    @song_name_length = song_name.length
  end
end

a = Song.new('Rock around the clock')
b = Song.new('Bohemian Rhapsody')
c = Song.new('Minute Waltz')

puts a < b
puts b >= c
puts c > a
puts a.between?(c,b)

这是我到目前为止所拥有的。我正在尝试编写比较歌曲名称长度的代码。

4

2 回答 2

2

修复您的比较原语,使其与另一个类似属性进行比较:

  def <=>(other)
    song_name.length <=> other.song_name.length
  end
于 2013-02-26T06:07:30.227 回答
0

你做错了两件事。后面需要一个分号,class Song并且需要比较 the 的长度和 的长度,@song_nameother不是它other本身。你也不需要attr_accessor。将其更改为attr_reader.

class Song; include Comparable
  attr_reader :song_name
  def <=>(other)
    @song_name.length <=> other.song_name.length
  end

  def initialize(song_name)
    @song_name = song_name
    @song_name_length = song_name.length
  end
end
于 2013-02-26T06:08:46.170 回答