在循环遍历文本行时,如何使用if语句(或类似语句)检查字符串是否为单个单词?检查字符串是否包含一个或多个字
def check_if_single_word(string)
# code here
end
s1 = "two words"
s2 = "hello"
check_if_single_word(s1) -> false
check_if_single_word(s2) -> true
在循环遍历文本行时,如何使用if语句(或类似语句)检查字符串是否为单个单词?检查字符串是否包含一个或多个字
def check_if_single_word(string)
# code here
end
s1 = "two words"
s2 = "hello"
check_if_single_word(s1) -> false
check_if_single_word(s2) -> true
既然你问的是'最Ruby的方式,我的方法重命名为single_word?
一种方法是检查是否存在空格字符。
def single_word?(string)
!string.strip.include? " "
end
但是,如果你想允许一组特定的满足您的定义字,也许还包括撇号和连字符的字符,使用正则表达式:
def single_word?(string)
string.scan(/[\w'-]+/).length == 1
end
我会* * 1 *给你的第一个代码...... :)这是'string.include? “”。 –
我会检查字符串中是否存在空格。
def check_if_single_word(string)
return !(string.strip =~//)
end
.strip可除去会在开始和字符串的末尾存在过量的空白。
!(myString =~//)
表示该字符串与单个空格的正则表达式不匹配。 同样,你也可以使用!string.strip[/ /]
。
这里是一些代码可以帮助你:
def check_if_single_word(string)
ar = string.scan(/\w+/)
ar.size == 1 ? "only one word" : "more than one word"
end
s1 = "two words"
s2 = "hello"
check_if_single_word s1 # => "more than one word"
check_if_single_word s2 # => "only one word"
def check_if_single_word(string)
string.scan(/\w+/).size == 1
end
s1 = "two words"
s2 = "hello"
check_if_single_word s1 # => false
check_if_single_word s2 # => true
我喜欢第三行“:”的布尔选项。给予好评! –
一个Ruby之道。扩展CALSS String
class String
def one?
!self.strip.include? " "
end
end
然后使用"Hello world".one?
检查是否字符串包含一个或多个字。
你不需要使用'self' ... –
我不会推荐给初学者修改内建函数。我也不会推荐“one?”这个名字,因为它不够明确。 –
另外,您有错误。尝试在irb中执行此操作,您会看到它。 –
按照你的意见给予了这个词的定义:
[A] stripped string that doesn't [include] whitespace
代码将
def check_if_single_word(string)
string.strip == string and string.include?(" ").!
end
check_if_single_word("two words") # => false
check_if_single_word("New York") # => false
check_if_single_word("hello") # => true
check_if_single_word(" hello") # => false
strip == self - 你使用方法'strip'作为独立的对象吗?这可以用所有方法完成吗?我第一次看到这个。 –
这是一个错误。 – sawa
我第一次看到另一个有趣的事情,在声明之后作为一种方法否定。那么//string.include?(“”)。! ==!string.include?(“”)//? –
第一修剪字符串,则搜索空间,或匹配正则表达式。我不知道红宝石,所以不能提供代码。 – Bathsheba
这为什么值得一个-1?如果我们不能用这个论坛来问简单的问题,那为什么不呢? –
我不是downvoter(或upvoter),但这个问题可以被解释为在你提出问题之前进行的研究水平的边界。 – Bathsheba