Ruby Basics
Ruby is strongly typed and dynamically typed
irb # run in command line
ibj = object.new
obj.class
obj.class.superclass
obj.methods
foo = 5
# Print string
# "#{var}"
p "Hello, #{foo}!"
# Or
p 'Hello, ' + foo.to_s + '!'
def obj:talk(message, prefix="echo-")
puts "#{prefix}#{message}"
end
obj.talk("my message")
# Or
obj.send("talk", "my message")
1 == 1.0 #=> true value equality
1.eql? 1.0 #=> false hash key equality
1.equal? 1.0 #=> false check reference equality
# EVERYTHING IS AN OBJECT!!!
# Numerics: integer and float
# -= and +=
# for loop: each, step, range
# same object_id for difference instance of 1
# String
hello << '!' # appending
#destructive methids
str.upcase # return without modifying the object
str.upcase! # return with modified object
to_s
to_i
to_f
# Symbol: string with immutable copy
a= :long # denoted with colon
to_sym
# TrueClass and FalseClass
# If Statements
foo = if true
1
elsif false
2
else
3
end
# Unless Statement
unless false
p "hello"
end
# One liners
p "hello" if true
p true ? 'hello': 'goodbye'
# Arrays and Hashes
# Array: auto-adjusted length, heterogeneous elements
a = []
a << 1
# Iterators
arr = [1,2,'john']
arr.each do |item|
puts "#{item}"
end
arr.each_with_index do |item, i|
puts "#{i} - #{item}"
end
# Block
[1,2,3].each {|n| print "#{n}"}
# ranges
(-5..-1).to_a #[-5,-4,-3,-2,-1]
('a'..'e').to_a #['a','b','c','d','e']
(2..100).each {|x| puts "#{x}"}
(2..100).step(2) {|x| puts "#{x}"}
#Hashes
foo = {}
foo[:hello] = "world"
p foo[:hello]
foo = {
foo: 'bar',
baz: 'foobar'
}
foo.each {|key, val| puts "#{val} + #{key}"}
foo.each_with_index {|(key, val), index| puts "#index: #{val} + #{key}"}
# Methods
def hi (name)
'hello, #{name}'
end
# return the lass excuted expression
# Mathods end in ? (return a boolean), = (write to a variable), ! (perform operation inplace on the object)
#Default argument
def hi (name = "Simon")
'hello, #{name}'
end
#Optional argument
def hi (*name)
p name
end
# hi() -> []
# hi(1,2,3) -> [1,2,3]
# Gems
# The Bundler Gem for managing other gems
# The Pry Gem for debuging
# The Rubocop Gem for grading for style
# The RSpec Gem
#