2012-08-16 103 views
3

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

当创建一个类,例如:

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方法打印出变量的值?

回答

0

除噶大山的媒体链接方位的答案,这里是你会做的方式以最佳状态

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 
+0

例如,您也可以使用'#@ var'代替#{@ var}'。全局变量相同('#$ var')。 – 2012-08-16 14:42:33

8

你应该将你的变量初始化到initialize

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

你有它在你的问题的方式,变量类的实例变量(你可以谷歌,如果你好奇,但它不是这里真的很重要)。

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

为了让您Print()工作的第二个版本,你需要用在#{}的变量,让他们插:

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

我觉得的Darshan计算已经解决你的问题非常好。但在这里我想给你另外的方法来实现这一点。

我假设你想打印出你在班上所有的实例变量。方法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