4

私の問題はおそらく非常に簡単ですが、どこにも答えが見つかりませんでした。

クラスを作成するとき、例えば:

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メソッドに変数の値を出力させるにはどうすればよいですか?

4

3 に答える 3

9

変数の初期化を次の場所に移動する必要がありますinitialize

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

あなたの質問にあるように、変数はクラスインスタンス変数です(興味があればGoogleで検索できますが、ここではあまり関係ありません)。

(通常の) インスタンス変数として初期化されPrint()ます。状態をダンプするだけの場合は、最初のバージョンの が機能します。各パラメーターがそれぞれの行に出力されます。

2 番目のバージョンをPrint()機能させるには、変数をラップ#{}して補間する必要があります。

def print # It's better not to capitalize your method names
  puts "#{@author}, #{@title}, #{@number_of_pages}"
end
于 2012-08-16T10:19:43.720 に答える
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
于 2012-08-16T14:35:24.627 に答える
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
于 2012-08-16T12:09:01.490 に答える