2012-08-16 241 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