使用Ruby比较两个字符串的长度
使用名为使用Ruby比较两个字符串的长度,ruby,string-length,Ruby,String Length,使用名为first的参数和名为second的参数定义名为first\u longer\u than\u second的方法。如果传入的第一个字大于或等于第二个字的长度,则该方法将返回true。否则返回false。下面是调用方法的方式和预期的返回: 这就是我所拥有的: def first_longer_than_second(first, second) if first.length >= second.length puts true else puts
first
的参数和名为second
的参数定义名为first\u longer\u than\u second
的方法。如果传入的第一个
字大于或等于第二个
字的长度,则该方法将返回true
。否则返回false。下面是调用方法的方式和预期的返回:
这就是我所拥有的:
def first_longer_than_second(first, second)
if first.length >= second.length
puts true
else
puts false
end
end
我得到了错误,我不知道为什么。Ruby比较运算符,如
=
自然返回布尔值。您不需要使用条件,而且几乎不希望返回与true
和false
等价的字符串。此外,Ruby约定在返回布尔值的方法名称中使用问号
对于这种方法,Ruby允许我们编写以下代码:
def first_longer_than_second?(first, second)
first.length >= second.length
end
然后您可以像这样调用该方法:
>> first_longer_than_second?('hello', 'sir')
=> true
请注意,方法名称有些混乱,因为如果
first
与second
的长度相同,则返回true。您可以考虑重新命名该方法。名字很重要 Ruby比较运算符,如=
自然返回布尔值。您不需要使用条件,而且几乎不希望返回与true
和false
等价的字符串。此外,Ruby约定在返回布尔值的方法名称中使用问号
对于这种方法,Ruby允许我们编写以下代码:
def first_longer_than_second?(first, second)
first.length >= second.length
end
然后您可以像这样调用该方法:
>> first_longer_than_second?('hello', 'sir')
=> true
请注意,方法名称有些混乱,因为如果
first
与second
的长度相同,则返回true。您可以考虑重新命名该方法。名字很重要 您可以发布您遇到的错误吗?请正确设置您的代码格式-在不知道错误的情况下在黑暗中拍摄,但是put
打印一行,然后返回nil
,这听起来不是你的方法应该做的…你能发布你得到的错误吗?请正确格式化你的代码-在不知道错误是什么的情况下在黑暗中拍摄,但是放置
打印一行,然后返回nil
,这听起来不是你的方法应该做的。。。