Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You posted the oneliner:</p> <pre><code>@sentence = @sentence.split(' ').map!{|x| x = x[0..0].upcase &lt;&lt; x[1..-1] }.join(' ') </code></pre> <p>But you misunderstand a couple things about Ruby.</p> <p>First off, saying <code>x=</code> in a map call doesn't affect anything outside of the map call. The new value of that array element is the value <em>returned</em> by the block.</p> <p>Secondly, you don't need to mutate the first string with <code>&lt;&lt;</code> -- a concatenation that creates a new string (using <code>+</code>) is a much better option.</p> <p>Thirdly, <code>map!</code> makes changes directly to the array returned by <code>split</code>. What you want to do is leave that array untouched (even though it doesn't change program semantics), and return a new array with the mapped results, by using <code>map</code>.</p> <p>So you should have written:</p> <pre><code>@sentence = @sentence.split(' ').map{|x| x[0..0].upcase + x[1..-1] }.join(' ') </code></pre> <p>Now the statement <code>x[0..0].upcase + x[1..-1]</code> is still very obtuse. Maybe you should replace it with the <code>capitalize</code> method, which already changes the first letter of the string to uppercase. (Note that it also downcases all of the others, which may or may not be what you want.)</p> <pre><code>@sentence = @sentence.split(' ').map{|x| x.capitalize }.join(' ') </code></pre> <p>I'd probably use <code>gsub!</code> to change parts of the string in-place, but that's probably a little obtuse:</p> <pre><code>@sentence.gsub!(/\S+/){|x| x.capitalize} </code></pre> <p>One more thing. If the only purpose of a block is to call a single method on the object passed to the block, you can do the following:</p> <pre><code>@sentence = @sentence.split(' ').map(&amp;:capitalize).join(' ') </code></pre> <p>or to modify my <code>gsub!</code> version:</p> <pre><code>@sentence.gsub!(/\S+/,&amp;:capitalize) </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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