2. Refinments
module
StringPatch
refine
String
do
def
is_number?
!!match(/^d+$/)
end
end
end
"1".is_number?
#
=>
undefined
method
`is_number?'
...
using
StringPatch
"1".is_number?
#
=>
true
"a".is_number?
#
=>
false
3. Refinments
$
ruby
string_patch.rb
string_patch.rb:2:
warning:
Refinements
are
experimental,
and
the
behavior
may
change
in
future
versions
of
Ruby!
4. Module#prepend
module
A
def
foo;
puts
"A";
end
end
class
B
include
A
def
foo;
puts
"B";
end
end
klass
=
B.new
klass.foo
#
=>
"B"
B.ancestors
#
=>
[B,
A,
Object,
Kernel,
BasicObject]
5. Module#prepend
module
A
def
foo;
puts
"A";
end
end
class
B
prepend
A
#
<-‐
prepend
instead
of
include
def
foo;
puts
"B";
end
end
klass
=
B.new
klass.foo
#
=>
"A"
B.ancestors
#
=>
[A,
B,
Object,
Kernel,
BasicObject]
7. Module#prepend
class
A
def
foo;
puts
"foo";
end
end
module
Extension
def
foo
super
puts
"bar"
end
end
class
A
prepend
Extension
end
A.new.foo
#
=>
"foo
bar"
A.ancestors
#
=>
[Extension,
A,
Object,
Kernel,
BasicObject]
12. Enumerable#lazy
words
=
File.open('/usr/share/dict/words')
.lazy
#
<-‐-‐
added
lazy
here
.map(&:chomp)
.reject
{
|word|
word.length
<
4
}
.take(10)
words
#
=>
#<Enumerator::Lazy:
...]
words.to_a
#
=>
["aalii",
"Aani",
"aardvark",
...]
#
time
ruby
lazy.rb
~
0.06s
13. Enumerable#lazy
require
"fruity"
range
=
1..100
compare
do
without_lazy
{
range.
map
{
|el|
el
*
2
}
}
with_lazy
{
range.lazy.map
{
|el|
el
*
2
}.to_a
}
end
#
Running
each
test
256
times.
#
without_lazy
is
faster
than
with_lazy
by
4x
±
0.1
14. %i and %I symbol literals
%i(foo
bar
baz)
#
=>
[:foo,
:bar,
:baz]
%I(foo
b#{2+2}r
baz)
#
=>
[:foo,
:b4r,
:baz]
15. Default source encoding is
UTF-8
#
Ruby
1.9
#
encoding:
utf-‐8
#
without
^
next
line
will
throw
"invalid
multibyte
char
(US-‐
ASCII)"
name
=
"Uģis
Ozols"
#
Ruby
2.0
name
=
"Uģis
Ozols"
16. #to_h
Ruby
=
Struct.new(:version)
ruby
=
Ruby.new("2.0")
ruby.to_h
#
=>
{
:version
=>
"2.0"
}
def
config(options)
if
options.respond_to?(:to_h)
#
consume
hash
else
raise
TypeErorr,
"Can't
convert
#{options.inspect}
into
Hash"
end
end
17. #respond_to? returns
false for protected methods
class
A
protected
def
foo
"A"
end
end
klass
=
A.new
klass.respond_to?(:foo)
#=>
false
klass.respond_to?(:foo,
true)
#=>
true
18. #require optimizations
Rails
4.0.0.beta1
application
rails
g
scaffold
user
name
time
rake
test Ruby
1.9.3-‐p392
~
12
seconds
time
rake
test Ruby
2.0.0-‐p0
~
5
seconds