Let's Learn Ruby - Basic
- 32. Let’s Learn Ruby
Rack
it’s a specification (and implementation) of a minimal
abstract Ruby API that models HTTP.
such as Sinatra, Ruby on Rails
Rack http://rack.rubyforge.org/
Sinatra http://www.sinatrarb.com
Ruby on Rails http://rubyonrails.org/
- 100. Let’s Learn Ruby
class Cat
def walk
puts "I'm walking"
end
end
!
cat = Cat.new
def cat.fly
puts "I can fly"
end
cat.fly
- 102. Let’s Learn Ruby
def method_missing(method_name)
puts "method: #{method_name} is called!"
end
!
something_not_exists()
- 104. Let’s Learn Ruby
def open_my_file(file_name)
File.open file_name do |f|
puts f.read
end
end
begin
open_my_file("block_demo.r")
rescue => e
puts e
else
puts "it's working good!"
ensure
puts "this must be executed, no matter what"
end
- 107. Let’s Learn Ruby
my_square = Proc.new { | x | x ** 2 }
!
# how to call a proc
puts my_square.call(10)
puts my_square[10]
puts my_square.(10)
puts my_square === 10
#
#
#
#
100
100
100
100
- 109. Let’s Learn Ruby
my_lambda = lambda { | x | x ** 2 }
!
# new style in 1.9
my_lambda = -> x { x ** 2 }
!
# how to call a lambda?
puts my_lambda.call(10)
puts my_lambda[10]
puts my_lambda.(10)
puts my_lambda === 10
#
#
#
#
100
100
100
100
- 111. Let’s Learn Ruby
def proc_test
puts "hello"
my_proc = Proc.new { return 1 }
my_proc.call
puts "ruby"
end
def lambda_test
puts "hello"
my_lambda = lambda { return 1 }
my_lambda.call
puts "ruby"
end
- 145. Let’s Learn Ruby
gem "nokogiri", :git => "git://github.com/
tenderlove/nokogiri.git"
gem "secret_gem", :path => "~/my_secret_path"
- 148. Let’s Learn Ruby
1. bundle gem NEW_NAME
2. gem build NEW_NAME.gemspec
3. gem push NEW_NAME.gem
http://guides.rubygems.org/make-your-own-gem/
- 151. Let’s Learn Ruby
desc "mail sender"
task :sendmail do
puts "grap mailing list from database..."
sleep 3
puts "mail sending..."
sleep 3
puts "done!"
end
- 152. Let’s Learn Ruby
task :goto_toliet do
puts "goto toliet"
end
!
task :open_the_door => :goto_toliet do
puts "open door"
end
- 154. Let’s Learn Ruby
require “minitest/autorun"
!
class TestMyBMI < MiniTest::Unit::TestCase
def test_my_calc_bmi_is_ok
assert_equal calc_bmi(175, 80), 26.12
end
end
!
def calc_bmi(height, weight)
bmi = ( weight / (height/100.0) ** 2 ).round(2)
end
- 155. Let’s Learn Ruby
require "minitest/autorun"
describe "test my bmi calculator" do
it "should calc the correct bmi" do
calc_bmi(175, 80).must_equal 26.12
end
end
def calc_bmi(height, weight)
bmi = ( weight / (height/100.0) ** 2 ).round(2)
end