我认为达山计算已经很好地解决了你的问题。但在这里,我想为您提供实现这一目标的替代方法。
我假设您想打印出类中的所有实例变量。方法instance_variables可以返回符号中所有 instance_variables 的数组。然后你可以迭代它们做任何你想做的事情。请注意:instance_variable_get 非常方便,但不是最佳实践。
class Book
attr_reader :author, :title, :number_of_pages
def initialize(author, title, number_of_pages)
@author = author
@title = title
@number_of_pages = number_of_pages
end
def print_iv(&block)
self.instance_variables.each do |iv|
name = iv
value = send(iv.to_s.gsub(/^@/, ''))
# value = instance_variable_get(iv) # Not recommended, because instance_variable_get is really powerful, which doesn't actually need attr_reader
block.call(name, value) if block_given?
end
end
end
rb = Book.new("Dave Thomas", "Programming Ruby - The Pragmatic Programmers' Guide", 864)
# rb.instance_variables #=> [:@author, :@title, :@number_of_pages]
rb.print_iv do |name, value|
puts "#{name} = #{value}"
end
#=> @author = Dave Thomas
#=> @title = Programming Ruby - The Pragmatic Programmers' Guide
#=> @number_of_pages = 864
# You can also try instance_eval to run block in object context (current class set to that object)
# rb.instance_eval do
# puts author
# puts title
# puts number_of_pages
# end