name = "Ruby" @name = "Ruby" @@count = 0 $global = "value" PI = 3.14159 :my_symbol arr = [1, 2, 3] hash = { key: "value", name: "Ruby" } (1..10) # 1 to 10 inclusive
(1...10) # 1 to 9 "Hello, #{name}!" str.length # or str.size str.upcase
str.downcase
str.capitalize "a,b,c".split(",") # ["a", "b", "c"] ["a", "b"].join("-") # "a-b" str.strip # both ends
str.lstrip # left
str.rstrip # right str.gsub("old", "new") str.include?("sub") if condition
# code
elsif other
# code
else
# code
end unless condition
# runs if condition is false
end result = condition ? "yes" : "no" case value
when 1
"one"
when 2, 3
"two or three"
else
"other"
end puts "yes" if condition while condition
# code
end until condition
# runs until condition is true
end for i in 1..5
puts i
end [1, 2, 3].each { |n| puts n } 5.times { |i| puts i } loop do
break if condition
end [1,2,3].each { |n| next if n == 2; puts n } def greet(name)
"Hello, #{name}!"
end def greet(name = "World")
"Hello, #{name}!"
end def greet(name:, age: 0)
"#{name} is #{age}"
end def sum(*numbers)
numbers.reduce(:+)
end # Last expression is returned
def add(a, b)
a + b
end [1, 2, 3].each do |n|
puts n
end [1, 2, 3].map { |n| n * 2 } def my_method
yield if block_given?
end my_proc = Proc.new { |n| n * 2 }
my_proc.call(5) # 10 my_lambda = ->(n) { n * 2 }
my_lambda.call(5) # 10 class Person
def initialize(name)
@name = name
end
end class Person
attr_reader :name # getter
attr_writer :age # setter
attr_accessor :email # both
end class Student < Person
def initialize(name, grade)
super(name)
@grade = grade
end
end class Person
def self.count
@@count
end
end module Greetable
def greet
"Hello!"
end
end class Person
include Greetable
end class Person
extend Greetable
end module MyApp
class User
end
end
MyApp::User.new [1, 2, 3].map { |n| n * 2 } # [2, 4, 6] [1, 2, 3, 4].select { |n| n.even? } # [2, 4] [1, 2, 3, 4].reject { |n| n.even? } # [1, 3] [1, 2, 3].reduce(0) { |sum, n| sum + n } # 6 [1, 2, 3].find { |n| n > 1 } # 2 [1, 2, 3].any? { |n| n > 2 } # true
[1, 2, 3].all? { |n| n > 0 } # true [3, 1, 2].sort # [1, 2, 3]
[3, 1, 2].sort.reverse # [3, 2, 1] [[1, 2], [3, 4]].flatten # [1, 2, 3, 4] [1, nil, 2, nil].compact # [1, 2] [1, 1, 2, 2].uniq # [1, 2] hash[:key]
hash.fetch(:key, "default") hash.keys
hash.values hash1.merge(hash2) hash.each { |k, v| puts "#{k}: #{v}" } hash.transform_values { |v| v.upcase } hash.select { |k, v| v > 10 } content = File.read("file.txt") lines = File.readlines("file.txt") File.write("file.txt", "content") File.open("file.txt", "a") { |f| f.puts "new line" } File.exist?("file.txt") File.delete("file.txt") begin
# risky code
rescue StandardError => e
puts e.message
end begin
# code
rescue TypeError
# handle
rescue ArgumentError
# handle
end begin
# code
rescue
# handle
ensure
# always runs
end raise "Error message"
raise ArgumentError, "Invalid argument" begin
# code
rescue
retry # try again
end