如何检查号码是否包含ruby中的其他号码?
示例:
number1 = 1321
number2 = 2
如何检查number1是否包含number2?
1321 contains 2 is true
答案 0 :(得分:3)
你可以做这样的事情来返回真或假
number1.to_s.include?(number2.to_s)
答案 1 :(得分:0)
这是字符串问题,而不是数字问题。数字不包含其他数字。您需要将两者都转换为字符串:
s1 = 1321.to_s # => "1321"
s2 = 2.to_s # => "2"
然后,只需使用[]
:
s1[s2] # => "2"
这将返回找到的索引值,或nil
:
s1["9"] # => nil
答案 2 :(得分:0)
另一种方法是将数字转换为字符串,并使用String#include?检查主字符串中是否存在子字符串:
number1 = 1321
number2 = 2
sn1 = number1.to_s
# => "1321"
sn2 = number2.to_s
# => "2"
"#{sn1} contains #{sn2} is #{sn1.include?(sn2)}"
# => "1321 contains 2 is true"
错误案例:
number1 = 1321
number2 = 9
sn1 = number1.to_s
# => "1321"
sn2 = number2.to_s
# => "9"
"#{sn1} contains #{sn2} is #{sn1.include?(sn2)}"
# => "1321 contains 9 is false"
答案 3 :(得分:0)
@meagar,可以被视为一个数字问题(某种程度上):
def number_in_number?(outer, inner)
test = 10**((inner < 2) ? 1 : Math.log10(inner).ceil.to_i)
while outer >= inner
return true if ((outer - inner) % test).zero?
outer /= 10
end
false
end
number_in_number?(1321, 2) #=> true
number_in_number?(1321, 32) #=> true
number_in_number?(1321, 4) #=> false
number_in_number?(1321, 1321) #=> true
number_in_number?(1321, 13211) #=> false
number_in_number?(543681321, 4368) #=> true
number_in_number?(543681321, 4367) #=> false