Tag: while循环

为什么Ruby的循环命令比true更慢?

Ruby有一个内置的loop命令,可以永久地执行它后面的块(或直到中断为止)。 但是,当它与function上相似while true ,它会明显变慢: require “benchmark/ips” NUMBER = 100_000_000 def fast index = 0 while true break if index > NUMBER index += 1 end end def slow index = 0 loop do break if index > NUMBER index += 1 end end Benchmark.ips do |x| x.report(“While Loop”) { fast } x.report(“Kernel loop”) { slow […]

尝试使用Ruby while循环查找字符串的元音

def count_vowels(string) vowels = [“a”, “e”, “i”, “o”, “u”] i = 0 j = 0 count = 0 while i < string.length do while j < vowels.length do if string[i] == vowels[j] count += 1 break end j += 1 end i += 1 end puts count end 我无法发现出错的地方。 如果该程序遇到辅音,它就会停止。 另外,使用“.each”方法如何解决同样的问题?