Idiosyncratic Ruby

Quiz


@JanLelisFebruary 2016RUG::B

idiosyncratic-ruby.com

Documenting lesser-known features in Ruby


Ruby String Magic Edition

Question 1

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?

Question 1

210

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)

Question 2

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?

Question 2

It unfreezes strings

string = "frozen string".freeze
string.object_id # => 19066860
string.frozen? # => true

copy = +string
copy.object_id # => 19012140
copy.frozen? # => false
            

Question 3

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"
            

Bonus Question 3

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"
            

Bonus Bonus Question 3

How to negate \p{Word}


"Rüben☃"[/???/] #=> "☃"
            

"Rüben☃"[/\p{^Word}+/] #=> "☃"
            

"Rüben☃"[/\P{Word}+/] #=> "☃"
            

Question 4

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

Question 4

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

URI.regexp

Ultimate Bonus Question 4


require 'uri'
string = URI.regexp.inspect.length # => ?
            

Ultimate Bonus Question 4


require 'uri'
string = URI.regexp.inspect.length # => 1454
            

This was Ruby Quiz #2

@JanLelis

MMM

Micro Modules Meetup

February 29, 2016 @ co-up 5th floor

DateTime edition