20

Can a Rails class name contain numbers? For example:

class Test123
end

Is this a valid class? I get an uninitialized constant Test123 error when I try to load the class.

Mohamad
  • 34,731
  • 32
  • 140
  • 219
Artem Kalinchuk
  • 6,502
  • 7
  • 43
  • 57

4 Answers4

63

I think Artem Kalinchuk's last comment deserves to be the answer of this misworded question.

A Ruby class name can contain numbers.

A Rails class has to be defined in a correctly named file. If I define a class called NewYear2012Controller:

Correct file name: new_year2012_controller.rb
Incorrect file name: new_year_2012_controller.rb (note the extra underscore)

Because this is how Rails inflector and auto-loading works.

lulalala
  • 17,572
  • 15
  • 110
  • 169
7

Yes, Ruby class names may contain numbers. However, as with all identifiers in Ruby, they may not begin with numbers.

Reference:

Identifiers

Examples:

foobar    ruby_is_simple

Ruby identifiers are consist of alphabets, decimal digits, and the underscore character, and begin with a alphabets(including underscore). There are no restrictions on the lengths of Ruby identifiers.

Community
  • 1
  • 1
Ry-
  • 218,210
  • 55
  • 464
  • 476
1

Try to do this:

  • rename your model and model.rb file
  • add table_name magic

as here:

class TwoProduct < ActiveRecord::Base
  self.table_name = '2_products'
end
bmalets
  • 3,207
  • 7
  • 35
  • 64
0

I don't know about this...

See the following

class Ab123
  def initialize(y) 
    @z = y 
  end
end

class AbCde
  def initialize(y) 
    @z = y 
  end
end

and the following instantiations:

Ab123.new x

or

AbCde.new x

Only the latter AbCde.new x instantiates properly.

rupweb
  • 3,052
  • 1
  • 30
  • 57
  • In Rails, it's one class per file if you want this to work properly, and the file name must match the class name using the appropriate rules. – matthew.tuck Jun 04 '21 at 06:17