101.ruby
strings_array = numbers_array.collect(&:to_s)
doubled_fibs = fibs.collect { |num| num * 2 }
ints = odds_n_ends.select { |x| x.is_a? Integer }
symbolize = lambda {|n| n.to_sym}
symbols = strings.collect(&symbolize)
Loops & Iterators
loop { print "Hello, world!" }
i = 20
loop do
i -= 1
next if i % 2 == 1
print "#{i}"
break if i <= 0
end
object.each { |item| # Do something }
object.each do |item|
# Do something
end
10.times { print "Chunky bacon!" }
i = 3
while i > 0 do
puts i
i -= 1
end
j = 3
until j == 0 do
puts j
j -= 1
end
for num in 1...10
puts num
end
Hashes, Symbols, Methods
Hashes
new_hash = { "one" => 1 }
new_hash = Hash.new
no_nil_hash = Hash.new("no_nil_hash")
animals = {
:dog => 1,
:cat => 17,
:canaries => 4,
:pig => 1
}
Symbols
Symbols are words that look just like variables. Again, they may contain letters, digits, or underscores. But they start with a colon.
"string" == :string # false
Symbols are lightweight strings. Usually, symbols are used in situations where you need a string but you won’t be printing it to the screen.
Constants
Constants are words like variables, but constants are capitalized. If variables are the nouns of Ruby, then think of constants as the proper nouns.
Constants can’t be changed after they are set.
EmpireStateBuilding = "350 5th Avenue, NYC, NY"
Methods
If variables and constants are the nouns, then methods are the verbs. Methods are usually attached to the end of variables and constants by a dot. You’ve already seen methods at work.
front_door.open
In the above, open is the method. It is the action, the verb. In some cases, you’ll see actions chained together.
front_door.open.close
We’ve instructed the computer to open the front door and then immediately close it.
front_door.is_open?
The above is an action as well. Both exclamation marks and question marks may be used in method names.
Like a boat pulling many inner tubes, methods with arguments can be chained.
front_door.paint( 3, :red ).dry( 30 ).close()
Blocks, Procs, and Lambdas
A block is just a bit of code between do..end
or {}
. It’s not an object on its own, but it can be passed to methods like .each
or .select
.
A proc is a saved block we can use over and over.
A lambda is just like a proc, only it cares about the number of arguments it gets and it returns to its calling method rather than returning immediately.
Procs
def batman_ironman_proc
victor = Proc.new { return "Batman will win!" }
victor.call
"Iron Man will win!"
end
puts batman_ironman_proc
Lambdas
def batman_ironman_lambda
victor = lambda { return "Batman will win!" }
victor.call
"Iron Man will win!"
end
puts batman_ironman_lambda
crew = {
captain: "Picard",
first_officer: "Riker",
lt_cdr: "Data",
lt: "Worf",
ensign: "Ro",
counselor: "Troi",
chief_engineer: "LaForge",
doctor: "Crusher"
}
first_half = lambda do |key,value|
value < "M"
end
a_to_m = crew.select(&first_half)
Object-Oriented Programming
class Language
def initialize(name, creator)
@name = name
@creator = creator
end
def description
puts "I'm #{@name} and I was created by #{@creator}!"
end
end
ruby = Language.new("Ruby", "Yukihiro Matsumoto")
python = Language.new("Python", "Guido van Rossum")
javascript = Language.new("JavaScript", "Brendan Eich")
ruby.description
python.description
javascript.description
class Application
def initialize(name)
@name = name
end
def create
puts "Hello, #{name} was created!"
end
end
class MyApp < Application
end
app = MyApp.new
app.create('webApp')
Public and Private methods in a Class
class Account
attr_reader :name, :balance
def initialize(name, balance=100)
@name = name
@balance = balance
end
def display_balance(pin_number)
puts pin_number == pin ? "Balance: $#{@balance}." : pin_error
end
def withdraw(pin_number, amount)
if pin_number == pin
@balance -= amount
puts "Withdrew #{amount}. New balance: $#{@balance}."
else
puts pin_error
end
end
private
def pin
@pin = 1234
end
def pin_error
"Access denied: incorrect PIN."
end
end
my_account = Account.new("Eric", 1_000_000)
my_account.withdraw(11, 500_000)
my_account.display_balance(1234)
my_account.withdraw(1234, 500_000)
my_account.display_balance(1234)
Related posts by tag
- 07 Nov 2024 daisyUI — Tailwind CSS Components
- 04 Mar 2024 Using personal gems with Bundle without bothering your colleagues.
- 12 Jul 2023 Protomaps - A serverless system for planet-scale maps