YCode YCode - 4 months ago 13x
Ruby Question

Ruby: creating a class object using the name of the class?

Please don't judge me too harshly because I am so new to this topic that I don't know how to ask the question (or what to search to get answers):

I am learning nested forms in Sinatra, but encountered something I don't understand which relates to Ruby.

See the code snippet below--while trying to test the code in

rake console
, I typed in
, and was surprised to see an object created with the name "Team". But if I type in
my_team = Team.new(params)
, I get an error message that
undefined local variable or method 'params' for main:Object

If I typed in anything else, say 'man', I get
NameError: undefined local variable or method 'man' for main:Object

Why does the name of the class result in an instance of the class? Shouldn't it require
to create an object?

class Team

attr_accessor :name
TEAM = []

def initialize(params)
@name = params[:team][:name]
TEAM << self

def self.all


In Ruby, everything is an object, thus classes are objects (and they are instances of the class Class.

Team is an instance of the class Class (shortened as "a class") whereas Team.new builds an instance of Team. Instances of Class have a certain behavior, which allows to create instances of themselves via the method #new.

Now, any arguments passed to a method in ruby must be defined in your current binding meaning that if params is undefined, you are not allowed to do Team.new(params) right off the bat. Defining a local variable (that will go into the binding) before accessing it is easy :

params = { team: { name: 'StackOverflow' } }

will work.