- http://globaldev.co.uk/2013/09/ruby-tips-part-2/
- http://globaldev.co.uk/2013/09/ruby-tips-part-3/
- http://globaldev.co.uk/2014/04/ruby-tips-part-5/
These are used all over the place within Ruby, but as an example #to_int is used to convert the argument to Array#[] to an int, and #to_str is used by raise when its argument isn’t an Exception.
class Line
def initialize(id)
@id = id
end
def to_int
@id
end
end
line = Line.new(2)
names = ["Central", "Circle", "District"]
names[line] #=> "District"& converts a Proc object into a block argument in a method call.
sum = Proc.new {|a, b| a + b}
(1..10).inject(&sum) #=> 55class Point
attr_accessor :x, :y
def initialize(x, y)
@x, @y = x, y
end
def self.to_proc
Proc.new {|ary| new(*ary)}
end
end
[[1, 5], [4, 2]].map(&Point) #=> [#<Point:0x007f87e983af40 @x=1, @y=5>, #<Point:0x007f87e983ace8 @x=4, @y=2>]module MyProject
class Error < StandardError
end
class NotFoundError < Error
end
def get
uri = URI('http://examp.cm/500')
response = Net::HTTP.get_response(uri)
raise NotFoundError, "#{uri} not found" if response.code == "404"
p response.body
rescue SocketError => e
raise e
end
end
class T
include MyProject
def test_get
begin
get
rescue MyProject::Error => e
p e
rescue => e
p e # Then you will get exeption here
end
end
endBut if you
module MyProject
Error = Module.new
class NotFoundError < StandardError
include Error
end
def get
uri = URI('http://examp.cm/500')
response = Net::HTTP.get_response(uri)
raise NotFoundError, "#{uri} not found" if response.code == "404"
p response.body
rescue SocketError => e
e.extend(Error)
raise e
end
end
class T
include MyProject
def test_get
begin
get
rescue MyProject::Error => e
p e # Then you could get exception from here, we know where it come from MyProject::NotFoundError or SocketError
end
end
endmodule T
module_function
def t
p 'ttt'
end
end
module A
extend self
def a
p 'aaa'
end
end
T.t # ttt
A.a # aaaconfig_path = File.expand_path("config.yml", __dir__)klass = Object.const_get(string)RBTree http://rbtree.rubyforge.org/