sinatra - Ruby: creating a class object using the name of the class? -
please don't judge me harshly because new topic don't know how ask question (or search answers):
i learning nested forms in sinatra, encountered don't understand relates ruby.
see code snippet below--while trying test code in rake console
, typed in team
, , surprised see object created name "team". if type in my_team = team.new(params)
, error message undefined local variable or method 'params' for main:object
if typed in else, 'man', nameerror: undefined local variable or method 'man' for main:object
why name of class result in instance of class? shouldn't require class_name.new
create object?
class team attr_accessor :name team = [] def initialize(params) @name = params[:team][:name] team << self end def self.all team end end
in ruby, object, classes objects (and instances of class class.
team
instance of class class (shortened "a class") whereas team.new
builds instance of team
. instances of class have behavior, allows create instances of via method #new
.
now, arguments passed method in ruby must defined in current binding meaning if params
undefined, not allowed team.new(params)
right off bat. defining local variable (that go binding) before accessing easy :
params = { team: { name: 'stackoverflow' } } team.new(params)
will work.
Comments
Post a Comment