class - ruby: Trouble understanding classes and defining variables with @ -
i doing rspec tutorial , having difficulties reading tests. current test trying read is:
describe book before @book = book.new end describe 'title' 'should capitalize first letter' @book.title = "inferno" @book.title.should == "inferno" end
i can understand asking me do: create class book , method inside class capitalize. thoughts on how code wrong (i have seen example of code works in case)
what tried do:
class book def initialize(book) @book = book end def title(@book) @book.capitalize end end
solution ended working:
class book attr_reader :title def initialize(title=nil) @title = title && title.capitalize! end def title=(new_title) @title = new_title && new_title.capitalize! end end
i not understand @ does. thought create variable works throughout entire class. in addition, wondering why @title used instead of @book (which specified in rspec test).
in addition, struggling "before do" part of code , why asks @book = book.new
also part && confusing well. why not ok put @title = title.capitalize!
i happy clarify of if not make sense (i know post long).
the @ fundamental construct in ruby: instance variable class. don't have pass param within methods of class. it's known entire instance of class. see, example, instance variables , accessors details.
so following isn't valid since don't pass instance variables method parameters:
def title(@book) @book.capitalize end
the &&
go second statement if first true or not nil
. example
def initialize(title=nil) @title = title && title.capitalize! end
will set class' instance variable @title
parameter title.capitalize!
long title
isn't nil
. if title
nil
, @title
set title
(i.e., nil
). if class created without parameter, @title
set nil
, error won't generated calling nil
method capitalize!
.
Comments
Post a Comment