RubyTapas #033 - #038
033 Classes and Constants
?
Point = Class.new do
attr_reader :x, :y
034 Struct from Hash
★
Beer = Struct.new(:brewery, :name, :abv, :ibu) do
def self.from_hash(attributes)
instance = self.new
attributes.each do |key, value|
instance[key] = value
end
instance
end
struct to hash
def attributes
result = {}
members.each do |name|
result[name] = self[name]
end
result
end
035 Callable
?
five different kinds of object which respond to the #call message
- A lambda
- A method object
- A symbol converted to a Proc
- A class implementing the #call method explicitly
- A test-specific lambda
036 Blocks, Procs, and Lambdas
★
greeter = Proc.new do |name|
greeter_p = proc do |name|
greeter_l = lambda do |name|
argumentの扱いが微妙に違う
returnがあって、最後のコードが実行されない
p = proc do
puts "In proc"
return
puts "After return"
end
l.call
p.call
puts "End of method"
"stabby lambda"
->(name) {
037 Proc and Threequals
★
threequals operator
You can match regular expressions, ranges, even classes with it
/\A\d+\z/ === "54321" # => true
(0..10) === 5 # => true
Numeric === 123 # => true
Procの===
even = ->(x){ (x % 2) == 0 }
even.call(2) # => true
even.call(3) # => false
even === 2 # => true
even === 3 # => false
caseで使われる
038 Caller-Specified Fallback
?
rescue => error
if block_given?
yield(error)
else
raise
end
end