简体   繁体   English

如何在Ruby中重写这个JavaScript循环?

[英]How would I rewrite this JavaScript loop in Ruby?

Code: 码:

var some_var = [/*.......*/];
var compare_var;
for (var i = 0; i < some_var.length - 1; i++){
    if (some_var[i] <= compare_var && compare_var < some_var[i + 1]){
        return some_var[i];
    }
}

One value of some_var is 30 and the next one is 40 and the next one is 50 and compare_var is 42. some_var一个值是30,下一个是40,下一个是50, compare_var是42。

It wouldn't return 30 even though it's less-than 42, because 42 isn't less-than 40. Which also means that it would return 40 because it's less-than 42 and 42 is less-than 50. 即使它小于42,也不会返回30,因为42不小于40。这也意味着它将返回40,因为它小于42,而42小于50。

Edit: 编辑:

As someone mentioned code translation is not exactly great for SE.so. 就像有人提到的那样,代码转换对SE.so来说并不是很好。 Just to make it clear: I did try several different things in ruby. 为了明确起见:我确实尝试了红宝石中的几种不同方法。 I have way more experience in javascript though, so the best way I could think of to phrase my question was to write what I needed out in javascript so that I could see how it translated into ruby. 我在javascript方面有更多的经验,所以我想表达我的问题的最佳方法是在javascript中写出我需要的内容,以便可以看到它如何转换成ruby。 Thanks for the answers 感谢您的回答

I would use the neato Enumerable#each_cons(n) method : 我会使用neato Enumerable#each_cons(n)方法

def foo(arr, x)
  arr.each_cons(2) do |a,b|
    return a if (a <= x) && (x < b)
  end
  nil # Not found
end

foo([30,40,50], 42) # => 40

This basically creates a "sliding window" of each pair and then you can just return the first item of the pair when you find the pair that encloses the target value (x). 基本上,这将为每个对创建一个“滑动窗口”,然后,当您发现包围目标值(x)的对时,可以只返回该对的第一项。

这是单线的:

some_var.select{|v| v < compare_var}.max

Get rid of var key word, change for loop into some_var.each , and you get a working code in Ruby. 摆脱var关键字,将for循环更改for some_var.each ,您将在Ruby中获得一个有效的代码。

PS. PS。 Code translation is not proper in StackOverflow 代码转换在StackOverflow中不正确

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

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