在 ruby 中打印对象的字符串
Printing a string of a object in ruby
我有这段代码,我想打印 'Make Breakfast' 而不是对象的 ID,我尝试了很多方法,但每次都打印 ID 而不是我想要的字符串.
require_relative 'Task'
class List
attr_reader :all_tasks
def initialize
@all_tasks = []
end
def add(task)
all_tasks << task
end
def show
all_tasks
end
end
if __FILE__ == $PROGRAM_NAME
my_list = List.new
puts 'You have created a new list'
my_list.add(Tasks.new('Make Breakfast'))
puts "You've added a item to the item list"
puts my_list.show
end
您可以在每个对象中定义一个 to_s
方法来更改它们的打印方式,在您的情况下,您希望 Task#to_s 显示任务中的文本,而 List#to_s 显示列表中的每个任务,可能将它们连接在一起:
# Inside Task
def to_s
all_tasks.map(&:to_s).join("\n")
end
map(&:to_s
) 将 return 一个数组,其中包含对每个任务调用 to_s
的结果,并且 join 将在它们之间换行。
我假设您的 Task
class.
中有一个 name
属性
class Task
attr_reader :name
def initialize(name)
@name = name
end
end
现在我们有一个 List
class 将有很多任务。我做了一个小改动。我所做的是添加一个 #to_s
方法。此方法将处理您的所有任务并提取它们的 name
属性。 #to_s
用于字符串“#{my_list}”插值和 puts
.
等地方
class List
attr_reader :all_tasks
def initialize
@all_tasks = []
end
def add(task)
all_tasks << task
end
def show
all_tasks
end
def to_s
# here i am using 'name' attribute on my assumption.
# map will make an array of names
# the join will join the array of names with ', '
all_tasks.map(&:name).join(', ')
end
end
if __FILE__ == $PROGRAM_NAME
my_list = List.new
puts 'You have created a new list'
my_list.add(Task.new('Make Breakfast'))
puts "You've added a item to the item list"
puts my_list # Note that i removed the all_tasks and using #to_s
end
我有这段代码,我想打印 'Make Breakfast' 而不是对象的 ID,我尝试了很多方法,但每次都打印 ID 而不是我想要的字符串.
require_relative 'Task'
class List
attr_reader :all_tasks
def initialize
@all_tasks = []
end
def add(task)
all_tasks << task
end
def show
all_tasks
end
end
if __FILE__ == $PROGRAM_NAME
my_list = List.new
puts 'You have created a new list'
my_list.add(Tasks.new('Make Breakfast'))
puts "You've added a item to the item list"
puts my_list.show
end
您可以在每个对象中定义一个 to_s
方法来更改它们的打印方式,在您的情况下,您希望 Task#to_s 显示任务中的文本,而 List#to_s 显示列表中的每个任务,可能将它们连接在一起:
# Inside Task
def to_s
all_tasks.map(&:to_s).join("\n")
end
map(&:to_s
) 将 return 一个数组,其中包含对每个任务调用 to_s
的结果,并且 join 将在它们之间换行。
我假设您的 Task
class.
name
属性
class Task
attr_reader :name
def initialize(name)
@name = name
end
end
现在我们有一个 List
class 将有很多任务。我做了一个小改动。我所做的是添加一个 #to_s
方法。此方法将处理您的所有任务并提取它们的 name
属性。 #to_s
用于字符串“#{my_list}”插值和 puts
.
class List
attr_reader :all_tasks
def initialize
@all_tasks = []
end
def add(task)
all_tasks << task
end
def show
all_tasks
end
def to_s
# here i am using 'name' attribute on my assumption.
# map will make an array of names
# the join will join the array of names with ', '
all_tasks.map(&:name).join(', ')
end
end
if __FILE__ == $PROGRAM_NAME
my_list = List.new
puts 'You have created a new list'
my_list.add(Task.new('Make Breakfast'))
puts "You've added a item to the item list"
puts my_list # Note that i removed the all_tasks and using #to_s
end