我尝试使用movies
方法迭代thumbs_up
数组并将其打印到屏幕上。
class Movie
def initialize(title,rank)
@title=title
@rank=rank
end
def thumbs_up
@rank+=1
end
def to_s
puts "your title is #{@title.to_s} and its rank is #{@rank.to_s} "
end
end
movie1 = Movie.new("Goonies", 6)
movie2 = Movie.new("Spun", 3)
movie3 = Movie.new("Hook", 2)
movies = [movie1, movie2, movie3]
movies.each do |x|
puts x.thumbs_up
puts x
end
我在输出后得到了像字符这样的额外错误。这是大部分正确的输出,但在我想要的输入后包含额外的东西:
your title is Goonies and its rank is 7
#<Movie:0x007fa6ba0e1da8>
4
your title is Spun and its rank is 4
#<Movie:0x007fa6ba0e1d58>
3
your title is Hook and its rank is 3
#<Movie:0x007fa6ba0e1d08>
我需要更改或删除它?
答案 0 :(得分:3)
您引用的输出实际上并非像“类似错误”字符那样的字符&#39;。它是一个对象。一种方法是从puts
方法中移除to_s
,但是除了修改其直接表示(例如,以某种格式输出某些内容)之外,它通常被认为是不好的做法。输出它作为句子的一部分)。更好,更模块化的方法如下:
class Movie
def initialize(title,rank)
@title = title
@rank = rank
end
def thumbs_up
@rank+=1
end
def thumbs_down
@rank-=1
end
attr_reader :title, :rank
attr_accessor :title
end
movie1 = Movie.new("Goonies",6)
movie2 = Movie.new("Spun",3)
movie3 = Movie.new("Hook",2)
movies = [movie1 ,movie2, movie3]
movies.each do |x|
x.thumbs_up
puts "Your title is #{x.title} and its rank is #{x.rank}"
end
这输出以下内容:
Your title is Goonies and its rank is 7
Your title is Spun and its rank is 4
Your title is Hook and its rank is 3
这可以通过attr_reader
类中的Movie
语句使用您公开的属性来实现。
答案 1 :(得分:0)
尝试从puts
方法移除to_s
。