Darshan Computingは、すでに問題を非常にうまく解決していると思います。しかし、ここでは、それを達成する別の方法を紹介したいと思います。
クラス内にあるすべてのインスタンス変数を出力したいと思います。メソッド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