检查 ruby​​ 中的字符长度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8753691/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 04:39:50  来源:igfitidea点击:

Checking character length in ruby

rubystring

提问by Vijay Sali

I got stuck in another situation: our users enter a text to be stored in a variable. The condition for that text is it can be allowed to enter only 25 characters, Now I have to write a regular expression which will check the condition, kindly help me out in this.

我陷入了另一种情况:我们的用户输入要存储在变量中的文本。该文本的条件是只能输入 25 个字符,现在我必须编写一个正则表达式来检查条件,请帮助我解决这个问题。

回答by Andrew Kirk

I think you could just use the String#length method...

我想你可以只使用 String#length 方法......

http://ruby-doc.org/core-1.9.3/String.html#method-i-length

http://ruby-doc.org/core-1.9.3/String.html#method-i-length

Example:

例子:

text = 'The quick brown fox jumps over the lazy dog.'
puts text.length > 25 ? 'Too many characters' : 'Accepted'

回答by Dan

Ruby provides a built-in function for checking the length of a string. Say it's called s:

Ruby 提供了一个用于检查字符串长度的内置函数。说它叫s

if s.length <= 25
  # We're OK
else
  # Too long
end

回答by elijah

Instead of using a regular expression, just check if string.length > 25

不使用正则表达式,只需检查 string.length > 25

回答by Kingsley Mitchell

Verification, do not forget the to_s

验证,别忘了to_s

 def nottolonng?(value)
   if value.to_s.length <=8
     return true
   else
     return false
   end
  end

回答by Gino

You could take any of the answers above that use the string.length method and replace it with string.size.

您可以采用上述任何使用 string.length 方法的答案并将其替换为 string.size。

They both work the same way.

它们的工作方式相同。

if string.size <= 25
  puts "No problem here!"
else
  puts "Sorry too long!"
end

https://ruby-doc.org/core-2.4.0/String.html#method-i-size

https://ruby-doc.org/core-2.4.0/String.html#method-i-size