调用方法中的方法以在Ruby中进行标题化 [英] Calling methods within methods to Titleize in Ruby

查看:99
本文介绍了调用方法中的方法以在Ruby中进行标题化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为编程任务创建标题方法,该方法将某些单词大写而忽略了其他单词。它总是首字母大写。为此,我制作了一个方法,该方法可以找到字符串的第一个单词,并尝试在titleize方法中调用它。我收到一条错误消息,提示警告:条件中的字符串文字。我尝试过更改if循环的用语,但这并不能解决我的错误。谁能向我解释为什么我的代码被破坏了?非常感谢您的帮助!

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


推荐答案

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

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

这是因为ruby解释器看到您的代码如下:

This happened as ruby interpreter sees your code as below:

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

第二个将始终为true,因为 '12'始终存在。警告是说,您有一个字符串文字,而不是 boolean test '12',始终计算为 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.

因此,修复方法如下:

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

这篇关于调用方法中的方法以在Ruby中进行标题化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆