打印变量

时间:2012-08-16 10:16:46

标签: ruby oop

我的问题可能很简单,但我无法在任何地方找到答案。

创建类时,例如:

class Book
  @author = "blabla"
  @title = "blabla"
  @number_of_pages"

我想创建一个打印变量的方法。在这里,当我尝试时,我遇到了问题:

def Print
  puts @author, @title, @number_of_pages
end

我一无所获。

当我尝试:

def Print
  puts "@author, @title, @number_of_pages"
end

我直截了当:“@ author,@ title,@ number_of_pages”

如何让Print方法打印出变量的值?

3 个答案:

答案 0 :(得分:9)

您应该将变量初始化移至initialize

class Book
  def initialize
    @author = "blabla"
    @title = "blabla"
    @number_of_pages = 42 # You had a typo here...
  end
end

你在问题​​中的方式,变量是类实例变量(如果你好奇的话可以使用Google,但这里并不重要)。

初始化为(正常)实例变量,如果您只是想要转储状态,则第一个版本的Print()可以工作 - 它会在自己的行上打印每个参数。

要使您的第二版Print()有效,您需要将变量包装在#{}中以进行插值:

def print # It's better not to capitalize your method names
  puts "#{@author}, #{@title}, #{@number_of_pages}"
end

答案 1 :(得分:1)

除了Darshan已经很出色的答案之外,以下是您最佳选择的方式

class Book

  attr_accessor :author, :title, :number_of_pages 
  #so that you can easily read and change the values afterward

  def initialize author, title, number_of_pages = nil 
    #so that you don't really need to provide the number of pages
    @author = author
    @title = title
    @number_of_pages = number_of_pages
  end

  def print
    puts "#{@author}, #{@title}, #{@number_of_pages}" 
  end 
end 

my_book = Book.new("blabla", "blabla", 42)
my_book.title = "this is a better title"
my_book.print

#=>blabla, this is a better title, 42

答案 2 :(得分:1)

我认为 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