Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Cribbing from the documentation (<a href="http://ruby-doc.org/core/classes/String.html#M001185" rel="nofollow">http://ruby-doc.org/core/classes/String.html#M001185</a>), here are answers to your two questions "why is the return value 'one t-three'" and "what does { $1[0, 1] } mean?"</p> <p><strong>What does { $1[0, 1] } mean?</strong> The method String#sub can take either two arguments, or one argument and a block. The latter is the form being used here and it's just like the method Integer.times, which takes a block:</p> <pre><code>5.times { puts "hello!" } </code></pre> <p>So that explains the enclosing curly braces.</p> <p>$1 is the substring matching the first capture group of the regex, as described <a href="http://blog.purifyapp.com/2010/01/04/cryptic-ruby-global-variables-and-their-meanings/" rel="nofollow">here</a>. [0, 1] is the string method "[]" which returns a substring based on the array values - here, the first character.</p> <p>Put together, { $1[0, 1] } is a block which returns the first character in $1, where $1 is the substring to have been matched by a capture group when a regex was last used to match a string.</p> <p><strong>Why is the return value 'one t-three'?</strong> The method String#sub ('substitute'), unlike its brother String#gsub ('globally substitute'), replaces the first portion of the string matching the regex with its replacement. Hence the method is going to replace the first substring matching "(t\w*)" with the value of the block described above - i.e. with its first character. Since 'two' is the first substring matching (t\w*) (a 't' followed by any number of letters), it is replaced by its first character, 't'.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload