什么是Ruby lower_bound?

tim*_*lly 0 ruby

所以我刚刚开始学习Ruby,并且不明白为什么每次我在终端中运行这段代码时输出等于16.对我来说,它没有意义,我真的想从中正确理解语法经验丰富的Rubyist.

def smallest_square(lower_bound)
  i = 0
  while true
    square = i * i

    if square > lower_bound
      return square
    end

    i = i + 1
  end
end

puts(smallest_square(10))
Run Code Online (Sandbox Code Playgroud)

tad*_*man 6

您的代码找到平方后的最小数字大于给定值.正方形的序列1,4,9,和16,所以图16是第一过线.

更Ruby的表达方式是:

 def smallest_square(lower_bound)
   (1..lower_bound).map do |i|
     i ** 2
   end.find do |i|
     i >= lower_bound
   end
 end
Run Code Online (Sandbox Code Playgroud)

问题是你可以通过简单的数学解决这个问题,不需要循环:

def smallest_square(lower_bound)
  Math.sqrt(lower_bound).ceil ** 2
end
Run Code Online (Sandbox Code Playgroud)

只是在下边界的平方根处或之上找到下一个正方形.