-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

比較プリミティブを修正して、他の属性の like 属性と比較するようにします。

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

あなたは2つのことを間違っています。後にセミコロンが必要であり、 自体ではなく のclass Song長さと の長さを比較する必要があります。も必要ありません。に変更します。@song_nameotherotherattr_accessorattr_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 に答える