ruby - syntax error, unexpected '=', expecting keyword_end -
i have code:
class tvshow attr_accessor :name attr_accessor :tvdbid def initialize(showname) :name = showname end end
and gives me error:
syntax error, unexpected '=', expecting keyword_end :name = showname
what i'm wanting have public variable can use across entire class, that's i'm trying :name , :tvdbid.
i'm new ruby, let me know if i'm doing wrong.
change:
def initialize(showname) :name = showname end
to
def initialize(showname) @name = showname end
you can this:
attr_accessor :name, :tvdbid
some examples:
class dog def initialize(name) @name = name end def show puts "i dog named: " + @name end def add_last_name(last_name) @name = @name + " " + last_name end end d = dog.new "fred" d.show d.add_last_name("rover") d.show --output:-- dog named: fred dog named: fred rover
so instance variables freely accessible within class. however, cannot access instance variables in example above outside class:
d = dog.new "fred" puts d.name --output:-- 1.rb:17:in `<main>': undefined method `name' #<dog:0x000001010a5b48 @name="fred"> (nomethoderror)
here how can access instance variables outside class:
class dog def initialize(name) @name = name end def name #getter @name end def name=(val) #setter @name = val end end d = dog.new "fred" puts d.name --output:-- fred
those getters , setters pain type--especially if have 10 instance variables--so ruby provides shortcut:
class dog def initialize(name, age) @name = name @age = age end attr_accessor :name, :age end d = dog.new("fred", 5) puts d.name puts d.age d.age = 6 #calls age=() method puts d.age --output:-- fred 5 6
but customary write attr_accessor line @ beginning of class.
Comments
Post a Comment