0
0
Rubyprogramming~5 mins

Ruby style guide essentials

Choose your learning style9 modes available
Introduction

Good style helps your code stay neat and easy to read. It makes working with others simpler and avoids confusion.

When writing Ruby code that others will read or maintain
When working on a team project to keep code consistent
When learning Ruby to build good habits early
When preparing code for sharing or publishing
When debugging to quickly understand what the code does
Syntax
Ruby
# Use 2 spaces for indentation
# Use snake_case for variable and method names
# Use CamelCase for class and module names
# Use meaningful names
# Use single quotes for simple strings, double quotes if you need interpolation
# End lines without semicolons

class MyClass
  def my_method
    message = 'Hello, world!'
    puts message
  end
end

Indentation is always 2 spaces, never tabs.

Keep lines under 80 characters for readability.

Examples
Method names use snake_case. Double quotes allow inserting variables inside strings.
Ruby
def greet_user(name)
  puts "Hello, #{name}!"
end
Class names use CamelCase. Use attr_accessor to create getter and setter methods.
Ruby
class UserProfile
  attr_accessor :name, :age
end
Variables use snake_case. Single quotes are fine when no variable inside string.
Ruby
user_name = 'alice'
puts 'Welcome, ' + user_name
Sample Program

This program defines a class with a method to greet a user by name. It shows proper naming and string use.

Ruby
class Greeter
  def initialize(name)
    @name = name
  end

  def greet
    puts "Hello, #{@name}!"
  end
end

greeter = Greeter.new('Bob')
greeter.greet
OutputSuccess
Important Notes

Always use meaningful names to make your code self-explanatory.

Avoid trailing whitespace at the end of lines.

Use empty lines to separate logical sections of code for clarity.

Summary

Use 2 spaces for indentation and snake_case for variables and methods.

Use CamelCase for classes and modules.

Choose single or double quotes based on whether you need string interpolation.