```svelte

Input Name

snake_case

Variables, methods, symbols, file names

ClassName

Classes, modules

CONSTANT

Constants, environment variables

Ruby Naming Conventions Explained

Ruby has a strong culture of following naming conventions. The Ruby style guide and RuboCop enforce these patterns to create readable, idiomatic Ruby code. Unlike JavaScript's camelCase, Ruby heavily favors snake_case for most identifiers.

snake_case - The Ruby Standard

Ruby uses snake_case (all lowercase with underscores) for variables, methods, and symbols. This is the most distinctive difference from languages like JavaScript and Java.

When to Use snake_case

  • Variables: user_name = 'Alice'
  • Methods: def get_user_data; end
  • Symbols: :user_profile
  • File Names: user_profile_controller.rb
  • Instance Variables: @current_user

Examples

# Variables
user_name = "Alice"
total_count = 0
is_authenticated = false

# Methods
def calculate_total(items)
  items.sum(&:price)
end

def fetch_user_data(user_id)
  User.find(user_id)
end

# Instance variables
class ShoppingCart
  def initialize
    @items = []
    @total_price = 0
  end

  def add_item(item)
    @items << item
    @total_price += item.price
  end
end

# Symbols
user = {
  first_name: "John",
  last_name: "Doe",
  email_address: "john@example.com"
}

PascalCase (CamelCase) - Classes and Modules

Ruby uses PascalCase for classes and modules. Each word starts with a capital letter, with no separators.

When to Use PascalCase

  • Classes: class UserAccount; end
  • Modules: module PaymentProcessor; end
  • Concerns: module Searchable; end

Examples

# Classes
class UserAccount
  attr_accessor :username, :email
  
  def initialize(username, email)
    @username = username
    @email = email
  end
end

class DatabaseConnection
  def self.establish
    # Connection logic
  end
end

# Modules
module Authentication
  def authenticate(credentials)
    # Auth logic
  end
end

module PaymentProcessor
  class CreditCard
    def charge(amount)
      # Charge logic
    end
  end
end

# Rails-style namespacing
module Api
  module V1
    class UsersController < ApplicationController
      # Controller actions
    end
  end
end

SCREAMING_SNAKE_CASE - Constants

Constants in Ruby use all uppercase letters with underscores. In Ruby, constants can be reassigned (with a warning), but the naming convention indicates they shouldn't be.

When to Use SCREAMING_SNAKE_CASE

  • Constants: MAX_USERS = 100
  • Configuration: API_BASE_URL = '...'
  • Environment Variables: DATABASE_URL
  • Class Constants: DEFAULT_TIMEOUT = 30

Examples

# Top-level constants
API_VERSION = "v1"
MAX_RETRY_ATTEMPTS = 3
DEFAULT_PAGE_SIZE = 20

# Class constants
class User
  MAX_USERNAME_LENGTH = 50
  VALID_ROLES = %w[admin user guest]
  DEFAULT_ROLE = 'user'
  
  def validate_username
    @username.length <= MAX_USERNAME_LENGTH
  end
end

# Configuration constants
module Config
  DATABASE_HOST = ENV['DB_HOST']
  DATABASE_PORT = ENV['DB_PORT']
  REDIS_URL = ENV['REDIS_URL']
end

Special Ruby Conventions

Predicate Methods (Boolean Returns)

Methods that return boolean values end with a question mark:

def authenticated?
  !current_user.nil?
end

def valid?
  errors.empty?
end

def empty?
  @items.empty?
end

# Usage
if user.authenticated?
  # Allow access
end

Dangerous Methods (Modify Receiver)

Methods that modify the object in place (rather than returning a copy) end with an exclamation mark:

# Non-mutating (returns new object)
def upcase
  @name.upcase
end

# Mutating (modifies original)
def upcase!
  @name.upcase!
end

# Example from Array
array = [3, 1, 2]
array.sort   # => [1, 2, 3]  (returns new array)
array        # => [3, 1, 2]  (original unchanged)

array.sort!  # => [1, 2, 3]  (modifies original)
array        # => [1, 2, 3]  (original changed)

Private Methods

Unlike JavaScript's underscore convention, Ruby has actual private methods. No naming convention needed:

class User
  def public_method
    private_method  # Can call from within class
  end
  
  private
  
  def private_method
    # This method is truly private
  end
end

Class vs Instance Variables

class User
  # Class variable (shared across all instances)
  @@total_users = 0
  
  # Class instance variable (belongs to the class object itself)
  @admin_count = 0
  
  def initialize(name)
    # Instance variable (unique to each instance)
    @name = name
    @@total_users += 1
  end
  
  # Class method
  def self.total_users
    @@total_users
  end
end

RuboCop Naming Rules

RuboCop is Ruby's most popular linter. Here are key naming rules it enforces:

# .rubocop.yml
Naming/MethodName:
  EnforcedStyle: snake_case

Naming/VariableName:
  EnforcedStyle: snake_case

Naming/FileName:
  EnforcedStyle: snake_case

Naming/ConstantName:
  Enabled: true

Naming/ClassAndModuleCamelCase:
  Enabled: true

Naming/PredicateName:
  ForbiddenPrefixes:
    - is_
    - have_
  # Ruby prefers bare adjectives: `empty?` not `is_empty?`

Rails-Specific Conventions

Ruby on Rails adds additional naming conventions:

Model Names

Singular PascalCase, table names are plural snake_case:

# Model: User (singular)
class User < ApplicationRecord
end

# Table: users (plural)
# File: app/models/user.rb

Controller Names

Plural PascalCase with "Controller" suffix:

# Controller: UsersController
class UsersController < ApplicationController
  def index
    @users = User.all
  end
end

# File: app/controllers/users_controller.rb

Association Names

class User < ApplicationRecord
  # Use snake_case for association names
  has_many :blog_posts
  has_one :user_profile
  belongs_to :organization
end

File Naming Conventions

Ruby files follow strict naming patterns:

  • Class UserProfileuser_profile.rb
  • Module PaymentProcessorpayment_processor.rb
  • Spec file: user_profile_spec.rb
  • Test file: user_profile_test.rb

Common Mistakes to Avoid

Mistake #1: Using camelCase for Methods

def getUserData; end

def get_user_data; end

Mistake #2: Using is_ Prefix for Booleans

def is_valid?; end (feels redundant in Ruby)

def valid?; end

Mistake #3: Lowercase Constants

max_users = 100 (looks like variable)

MAX_USERS = 100

Mistake #4: snake_case for Class Names

class user_account; end

class UserAccount; end

Ruby vs Other Languages

PurposeRubyJavaScriptPython
Variablesuser_nameuserNameuser_name
Methods/Functionsget_user_datagetUserData()get_user_data()
ClassesUserAccountUserAccountUserAccount
ConstantsMAX_USERSMAX_USERSMAX_USERS
Booleansvalid?isValidis_valid

Best Practices Summary

  • ✓ Use snake_case for all methods, variables, and file names
  • ✓ Use PascalCase only for classes and modules
  • ✓ Use SCREAMING_SNAKE_CASE for constants
  • ✓ End boolean methods with ?
  • ✓ End dangerous (mutating) methods with !
  • ✓ Prefer bare adjectives over is_ prefix for booleans
  • ✓ Use RuboCop to enforce style automatically
  • ✓ Follow Rails conventions for models/controllers if using Rails
  • ✓ Keep method names descriptive but concise
  • ✓ Avoid abbreviations unless widely understood

Converting from JavaScript to Ruby

When translating code from JavaScript to Ruby:

// JavaScript
function getUserProfile(userId) {
  const isValid = validateUser(userId);
  const userData = fetchData(userId);
  return userData;
}

# Ruby
def get_user_profile(user_id)
  is_valid = validate_user(user_id)
  user_data = fetch_data(user_id)
  user_data
end

# More idiomatic Ruby (with ?)
def user_valid?(user_id)
  validate_user(user_id)
end

Metaprogramming Conventions

Ruby's metaprogramming features follow naming conventions too:

class User
  # attr_accessor creates getter and setter methods
  attr_accessor :name, :email
  
  # Equivalent to:
  def name
    @name
  end
  
  def name=(value)
    @name = value
  end
  
  # Setter methods end with =
  def username=(value)
    @username = value.downcase
  end
end
```