My problem is probably quite easy, but I couldn't find an answer anywhere.
When create a class, for example:
class Book
@author = "blabla"
@title = "blabla"
@number_of_pages"
I want to create a method to print out my variables. And here I'm getting a problem when I try:
def Print
puts @author, @title, @number_of_pages
end
I am getting nothing.
When I try:
def Print
puts "@author, @title, @number_of_pages"
end
I get straight: "@author, @title, @number_of_pages"
How can I make the Print
method print out the variables' values?
You should move your variable initializations to initialize
:
class Book
def initialize
@author = "blabla"
@title = "blabla"
@number_of_pages = 42 # You had a typo here...
end
end
The way you have it in your question, the variables are class instance variables (which you can Google if you're curious about, but it's not really relevant here).
Initialized as (normal) instance variables, your first version of Print()
works if you're just looking to dump the state -- it prints each parameter on its own line.
To make your second version of Print()
work, you need to wrap your variables in #{}
to get them interpolated:
def print # It's better not to capitalize your method names
puts "#{@author}, #{@title}, #{@number_of_pages}"
end
In addition to the allready exellent answer of Darshan, here is the way you would do it optimally
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With