Documenting lesser-known features in Ruby
A new syntax for creating strings has been introduced in Ruby 2.3
string = <<~RUGB
squiggly heredoc
RUGB
string # => "squiggly heredoc\n"
How many syntaxes exist to create strings in Ruby?
double quoted literal (1 way)
single quoted literal (1 way)
single char literal (1 way)
heredocs (9 ways)
%Q[]
syntax (66 ways)
%q[]
syntax (66 ways)
%[]
syntax (66 ways)
Ruby has a unary plus operator
+42 # => 42
For a long time it had no function
"[The unary plus] is provided for symmetry with unary minus, and can, of course, be redefined."
From Ruby 2.3 on, it finally does something. What?
It unfreezes strings
string = "frozen string".freeze
string.object_id # => 19066860
string.frozen? # => true
copy = +string
copy.object_id # => 19012140
copy.frozen? # => false
In a regex, \w
will match word characters
More specifically, it will only match ASCII characters
"Rüben☃"[/\w+/] #=> "R"
How to also match Unicode characters with \w
?
"Rüben☃"[/(?u)\w+/] #=> "Rüben"
What other ways are there to match Unicode word characters?
"Rüben☃"[/[[:word:]]+/] #=> "Rüben"
"Rüben☃"[/\p{Word}+/] #=> "Rüben"
"Rüben☃"[/\p{wORD}+/] #=> "Rüben"
How to negate \p{Word}
"Rüben☃"[/???/] #=> "☃"
"Rüben☃"[/\p{^Word}+/] #=> "☃"
"Rüben☃"[/\P{Word}+/] #=> "☃"
How to find URLs in text? (fill in)
require '___'
string = "Visit http://idiosyncratic-ruby.com/20-better-standards.html for a" \
"comprehensive quick list of the standard library!"
puts string._________________.to_a.compact
http://idiosyncratic-ruby.com/20-better-standards.html
http
idiosyncratic-ruby.com
/20-better-standards.html
How to find URLs in text? (fill in)
require 'uri'
string = "Visit http://idiosyncratic-ruby.com/20-better-standards.html for a" \
"comprehensive quick list of the standard library!"
puts string.match(URI.regexp).to_a.compact
http://idiosyncratic-ruby.com/20-better-standards.html
http
idiosyncratic-ruby.com
/20-better-standards.html
require 'uri'
string = URI.regexp.inspect.length # => ?
require 'uri'
string = URI.regexp.inspect.length # => 1454
February 29, 2016 @ co-up 5th floor