Note that there are some explanatory texts on larger screens.

plurals
  1. POsplit-related functionalities
    text
    copied!<p>I use ruby 1.9.2.</p> <p><code>gsub</code>/<code>scan</code> iterate over matches to a given regex/string, and is used in three ways:</p> <ol> <li>If <code>scan</code> is used without a block, it returns an array of matches.</li> <li>If <code>scan</code> is used with a block, it iterates over matches and performs something.</li> <li>If <code>gsub</code> is used, it replaces the matches with what is given as the second argument or as the block, and returns a string.</li> </ol> <p>On the other hand, there is <code>split</code> that matches the complement of what <code>gsub</code>/<code>scan</code> match. However, there is only one way to use this:</p> <ol> <li>If <code>split</code> is used without a block, It returns an array of the complement of the matches.</li> </ol> <p>I wanted the other two missing usages related to <code>split</code>, and tried to implement them. The following <code>every_other</code> extends <code>split</code> so that it can be used like <code>scan</code>.</p> <pre><code>class String def every_other arg, &amp;pr pr ? split(arg).to_enum.each{|e| pr.call(e)} : split(arg) end end # usage: 'cat, two dogs, horse, three cows'.every_other(/,\s*/) #=&gt; array 'cat, two dogs, horse, three cows'.every_other(/,\s*/){|s| p s} # =&gt; executes the block </code></pre> <p>Then, I tried to implement the counterpart of <code>gsub</code>, but cannot do it well.</p> <pre><code>class String def gsub_other arg, rep = nil, &amp;pr gsub(/.*?(?=#{arg}|\z)/, *rep, &amp;pr) end end # usage 'cat, two dogs, horse, three cows'.gsub_other(/,\s*/, '[\1]') # or 'cat, two dogs, horse, three cows'.gsub_other(/,\s*/) {|s| "[#{s}]"} # Expected =&gt; "[cat], [two dogs], [horse], [three cows]" # Actual output =&gt; "[cat][],[ two dogs][],[ horse][],[ three cows][]" </code></pre> <ul> <li>What am I doing wrong?</li> <li>Is this approach correct? Is there a better way to do it, or are there already methods that do this?</li> <li>Do you have suggestions about the method names?</li> </ul>
 

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