Skip to content

Ruby Cheatsheet

homepage-banner

Introduction

Ruby is a popular programming language that is known for its simplicity and productivity. Developed in the mid-1990s, it has become one of the most used languages worldwide. In this blog post, we will introduce you to the basics of the Ruby language in just 30 minutes.

Introduction to Syntax

ruby test.rb

Interactive Execution

irb
irb --simple-prompt

' and "

Similar to bash, variables in single quotes are not interpreted

Encoding

# encoding: UTF-8

In Ruby 2.0, if you want your code to be encoded in UTF-8, you can omit the magic comment.

ruby -E UTF-8 script_filename
irb -E UTF-8

The puts method differs slightly from the print method in that the puts method always outputs a newline character at the end of the result.

## Direct output
print "Hello, Ruby.\n"
## Separated same-line output
print "Hello, ", "Ruby", ".", "\n"
## Separated new-line output
puts "Hello, ", "Ruby!"
## When using the p method, numeric and string results are output in different forms
p "100"
p 100

Variables and Calculations

Math.sin(3.1415)
Math.sqrt(10000)
x = 10
y = 20
z = 30
area = (x*y + y*z + z*x) * 2
volume = x * y * z
## You can use #{variable name} in a string to do this
print " Area = #{area}\n"
print " Area = #{(x*y + y*z +z*x) * 2}\n"

Comments

# Use # to indicate a comment on that line

=begin
Block
Comment
=end

Control statements

a = 20
if a >= 10 then
    print "greater\n"
else
    print "smaller\n"
end

Loops

i = 1
while i <= 10
    print i, "\n"
    i = i + 1
end
## The times method is called an iterator

100.times do
  print "try iterator\n"
end

Objects

Arrays

Objects that store objects like arrays and hashes are called containers.

names = [" AA ", " B ", " CCC ", " D "]
names[0]
num = [3, 1, 4, 1, 5, 9, 2, 6, 5]
## Size of the array
num.size

## each traversal
names.each do |n|
    puts n
end

Hash

In Ruby, symbols are very similar to strings, symbols are also objects, usually used as name tags to represent the objects of methods, etc.

sym = :foo
sym2 = :"foo"

## Symbols and strings can be converted to each other
>> sym = :foo
=> :foo
>> sym = :foo
=> :foo
>> sym.to_s
=> "foo"
>> "foo".to_sym
=> :foo

## Conversion between strings and numbers
ARGV[0].to_i
"5".to_i

Hash creation

song = { :title => "Paranoid Android", :artist => "Radiohead"}
mark = { 11 => "Jack", 12 => "Queen", 13 => "King"}
person1 = { :name => " HT", :pinyin => "houteng"}
person2 = { name: " HT", pinyin: "houteng"}

Hash usage

address = {name: " GQ", pinyin: "gaoqiao"}
address[:name]
address[:pinyin]
address[:tel] = "000-1234-5678"
address

Hash loop

address.each do |key, value|
    puts "#{key}: #{value}"
end

Regular Expressions

Patterns and Matching

When only English, numbers, and Chinese characters are used in the pattern, if the string to be matched contains the string in the pattern, it is considered a successful match, otherwise it is considered a match failure. If the match is successful, the position of the matching part is returned. The position of the character is counted starting from 0, just like the index of an array. That is to say, the first character position of the string is 0. Conversely, if the match fails, nil is returned.

## /pattern/ =~ string to be matched

/Ruby/ =~ "Yet Another Ruby Hacker,"
/Ruby/ =~ "Ruby"
/Ruby/ =~ "Diamond"

## The /i after the regular expression indicates a case-insensitive match.
/Ruby/ =~ "ruby"
/Ruby/i =~ "ruby"
/Ruby/i =~ "rUbY"

Command Line and Files

Data Input from Command Line

print_argv.rb

puts " First argument: #{ARGV[0]}"
puts " Second argument: #{ARGV[1]}"
puts " Third argument: #{ARGV[2]}"
puts " Fourth argument: #{ARGV[3]}"
puts " Fifth argument: #{ARGV[4]}"
ruby print_argv.rb 1st 2nd 3rd 4th 5th

Reading Content from Files

read_text.rb

filename = ARGV[0]
file = File.open(filename)
text = file.read
print text
file.close
ruby read_text.rb FILE

read_text_simple.rb

filename = ARGV[0]
text = File.read(filename)
print text

read_text_oneline.rb

print File.read(ARGV[0])

Reading File Line by Line

read_line.rb

filename = ARGV[0]
file = File.open(filename)
file.each_line do |line|
    print line
end
file.close

Extracting Target Lines

simple_grep.rb

pattern = Regexp.new(ARGV[0])
filename = ARGV[1]
file = File.open(filename)
file.each_line do |line|
    if pattern =~ line
        print line
    end
end
file.close
ruby simple_grep.rb pattern filename

Methods

hello_ruby2.rb

def hello
    puts "Hello, Ruby."
end
hello()
ruby hello_ruby2.rb

Referencing Other Libraries or Packages

require "date"
days = Date.today - Date.new(1993, 2, 24)
puts(days.to_i)

In addition to the p method, Ruby also provides another method called pp, which has a similar effect. pp is an abbreviation for prettyprint in English. To use the pp method, we need to use the require method to reference the pp library.

require "pp"
books = [
    { title: " AA", author: "BBB" },
    { title: "BBB", author: " HAHU" },
    { title: "CCCCC", author: "Paul Gallico" },
]

p books
pp books

Variables Constants and Keywords

Variables

  • Local variables: beginning with a lowercase English letter or _.
  • Global variables: beginning with $.
  • Instance variables: beginning with @.
  • Class variables: beginning with @@.
  • Pseudo-variables: nil, true, false, self, etc.

Constants

Constants begin with a capital English letter. For example, Ruby’s running version (RUBY_VERSION), running platform (RUBY_PLATFORM), command line parameter array (ARGV), etc. are all predefined constants in Ruby.

Keywords

__LINE__
__ENCODING__
__FILE__
BEGIN
END
alias
and
begin
break
case
class
def
defined?
do
else
elsif
end
ensure
false
for
if
in
module
next
nil
not
or
redo
rescue
retry
return
self
super
then
true
undef
unless
until
when
while
yield

Multiple Assignments

a, b, c = 1, 2, 3
## Add an asterisk before the variable name to have Ruby wrap the unassigned values into an array and assign it to that variable.
a, b, *c = 1, 2, 3, 4, 5
## Swap variables
a, b = b, a
ary = [1, 2]
a, b = ary

Classes

Class Definitions

class HelloWorld
  def initialize(myname = "Ruby")
    @name = myname
  end
  def hello
    puts "Hello, world. I am #{@name}."
  end
end
bob = HelloWorld.new("Bob")
alice = HelloWorld.new("Alice")
ruby = HelloWorld.new

bob.hello

Class Methods

class << HelloWorld
  def hello(name)
      puts "#{name} said hello."
  end
end

## Or

class HelloWorld
  class << self
    def hello(name)
        puts "#{name} said hello."
    end
  end
end

## Or

class HelloWorld
  def self.hello(name)
      puts "#{name} said hello."
  end
end
  • initialize method is equivalent to __init__ in Python
  • @name instance variable
  • @@count class variable is a shared variable for all instances of the class

public, private and protected

class AccTest
  def pub
    puts "pub is a public method."
  end
  public :pub
  def priv
    puts "priv is a private method."
  end
  private :priv
end

acc = AccTest.new
acc.pub
acc.priv

Class and Object Judgment

### To determine if an object belongs to a class
ary = []
str = "Hello world."
p ary.instance_of?(Array)
p str.instance_of?(String)
p ary.instance_of?(String)
p str.instance_of?(Array)

### To trace back whether an object belongs to a class based on the class's inheritance relationship
str = "This is a String."
p str.is_a?(String)
p str.is_a?(Object)

Modules

Creating Modules

module HelloModule
  Version = "1.0"           # Define constant
  def hello(name)           # Define method
    puts "Hello, #{name}."
  end
  module_function :hello    # Specify hello method as module function
end

p HelloModule::Version      #=> "1.0"
HelloModule.hello("Alice")  #=> Hello, Alice.

include HelloModule         # include module
p Version                   #=> "1.0"
hello("Alice")              #=> Hello, Alice.

Reference

  • https://github.com/ThibaultJanBeyer/cheatsheets/blob/master/Ruby-Cheatsheet.md
Feedback







Disclaimer
  • Welcome to visit the knowledge base of SRE and DevOps!
  • License under CC BY-NC 4.0
  • Made with Material for MkDocs and improve writing by generative AI tools
  • Copyright issue feedback me#imzye.com, replace # with @