繁体   English   中英

Ruby返回错误的类型

[英]Ruby return wrong type

def starts_with_consonant?(str)
    str.empty? || str.class != String ||  /\A[^aeiou]/i=~str
end
p starts_with_consonant? "Apple" #=>nil
p starts_with_consonant? "microsoft"#=> 0

我希望它返回true或false,但返回nil和0。

这是因为在匹配的情况下,最后一个表达式中的Regex测试返回nil或0。 您需要将比赛强制为布尔值

def starts_with_consonant?(str)
   str.empty? || str.class != String ||  (/\A[^aeiou]/i=~str != nil)
end

在Ruby中,除了nilfalse之外,每个对象都被视为true(truthy)。 其中包括0:

puts '0 is true' if 0
0 is true

出于所有目的和目的,您的代码已返回false和true,它将与if或boolean运算符(如&&||一起正常使用 只有直接比较才会显示出差异:

starts_with_consonant? "Apple" == false
=> false

但是,Ruby中的任何东西都不需要进行这种比较,并且通常被认为是不好的风格。 只需使用ifunless

if starts_with_consonant? "Apple"
  #...
end

unless starts_with_consonant? "Apple"
  #...
end

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM