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

내가 바로 얻을 :

가 어떻게이 Print 방법은 변수 '값을 출력 할 수있다 "@author, @title을 @number_of_pages"?

답변

0

, 여기 당신이 할 것이 방법입니다 :

은, 당신이 그 (것)들을 보간 얻을 #{}에 변수를 포장 할 필요가 Print() 작업의 두 번째 버전을 만들려면 그것은 최적

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

예를 들어 vars는 '# {var}'대신 '# @ var'를 사용할 수도 있습니다. 전역 변수 ('# $ var')와 같습니다. –

8

당신은 initialize에 변수 초기화를 이동해야합니다 :

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

당신이 당신의 질문에이 방법을, 변수는 당신이에 대해 궁금 구글 수있는 경우 클래스 인스턴스 변수 (하지만 그렇지 않아 정말로 여기에서 관련이있다).

(보통) 인스턴스 변수로 초기화하면 상태를 덤프하려는 경우 Print()의 첫 번째 버전이 작동합니다. 각 매개 변수는 자체 줄에 인쇄됩니다.

이 DARSHAN의 allready 우수 대답에 추가
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