Calling methods within methods to Titleize in Ruby

安稳与你 提交于 2019-12-08 09:05:12

问题


I am trying to create a titleizing method for a programming assignment, it capitalizes certain words and ignores others. It always capitalizes the first word. To this end, I made a method that finds the first word of a string, and tried to call it within the titleize method. I'm getting an error that says "warning: string literal in condition". I've tried changing the phrasing of the if loop around, but it's not fixing my error. Can anyone explain to my why my code is broken? Thanks so much for your help!

def first_word(str)
    array = str.split(' ')
    return array[0]
end

def titleize(str)
    words = str.split
    words.each do |word| 
        if word != first_word(str)
            word.capitalize!
        elsif word != 'and' or 'the'
            word.capitalize!
        end
        words.join ' '
    end
end

回答1:


Change the following

elsif word != 'and' or 'the'

to

elsif word != 'and' or word != 'the'



回答2:


The operator != has higher precedence than or. It means that this line

elsif word != 'and' or 'the'

is equivalent to

elsif (word != 'and') or 'the'

and not to

elsif word != ('and' or 'the')

as you probably expected. The latter equivalence should be expressed as

elsif word != 'and' or word != 'the'

but even in this case it would not make a lot of sense and it's very hard to read.

You may want to change the link to

elsif !%w(and the).include?(word)



回答3:


str = 'abc'
p "hi" if str == '1' or '12'
#=> warning: string literal in condition

or

str = 'abc'
p "hi" if (str == '1' or '12')
#=> warning: string literal in condition
p "hi" if '12'
#=> warning: string literal in condition

This happened as ruby interpreter sees your code as below:

p "hi" if str == '1' or true

The second one will always evaluates to true, because '12' always exist. The warning is saying that instead of a boolean or test, you have a string literal, '12', which always evaluates to true.

So a fix is as below:

p "hi" if str == '1' or str == '12' #=> "hi"
p "hi" if ['1','12'].include? str #=> "hi"



回答4:


Not sure how readable this is. But it's short!

def titleize(str)
  str.capitalize.split.map do |word|
    %w{and the}.include?(word.downcase) ? word : word.capitalize
  end.join(' ')
end


来源:https://stackoverflow.com/questions/16129479/calling-methods-within-methods-to-titleize-in-ruby

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!