Question: Manual Titleize in Ruby 2.3.3

Question

Manual Titleize in Ruby 2.3.3

Answers 1
Added at 2017-07-24 00:07
Tags
Question

I'm trying to .capitalize all string inputs, excluding small words such as "Of", "The" or "And".

I can't figure out why the code isn't working properly.

def titleize(x)
  capitalized = x.split.each do |i|
    if i.length >= 2
      if i == "of" || "the" || "and"
        next
      else
        i.capitalize!
      end
    else
      next
    end
  end
  capitalized.join(' ')
end

Here's my Rspec output:

Failures:

 1) Simon says titleize capitalizes a word
 Failure/Error: expect(titleize("jaws")).to eq("Jaws")

   expected: "Jaws"
        got: "jaws"

   (compared using ==)
Answers to

Manual Titleize in Ruby 2.3.3

nr: #1 dodano: 2017-07-24 00:07

You have a string literal in condition warning in:

if i == "of" || "the" || "and"

You're trying to compare i with of or the or and, but after the first try, you're not passing a left value to compare, try with:

if i == "of" || i == "the" || i == "and"

More idiomatic Ruby would be to use include?

if ['of', 'the', 'and'].include?(i)

This way at least you get Jaws

The reason because your actual method doesn't work for the string war and peace is because if the length of the word being passed is minor or equal than 2 then it'll execute next, so, it'll only capitalize the word peace.

Source Show
◀ Wstecz