English 中文(简体)
3. 利用一系列阵列在鲁比拉进行搜索
原标题:Searching through arrays in Ruby using a range

i ve seen a lot of other questions touch on the subject but nothing as on topic as to provide an answer for my particular problem. Is there a way to search an array and return values within a given range... for clarity I have one array = [0,5,12] I would like to compare array to another array (array2) using a range of numbers. Using array[0] as a starting point how would I return all values from array2 +/- 4 of array[0].

在这一特定情况下,从2阵列返回的人数将在4-4和4之间。

感谢Ninjas的帮助。

最佳回答

构建一个范围,即你的具体目标±4,然后使用https://ruby-doc.org/core/Evidable.html#method-i-select” rel=“nofollow noretinger”> 无数可读的#select<>/code http://ruby-doc.org/french/Range.html

例如,让我们看一看一阵列中的11±4号,其中包括1至100号(包括):

a = (1..100).to_a
r = 11-4 .. 11+4
a.select { |i| r.include?(i) }
# [7, 8, 9, 10, 11, 12, 13, 14, 15]

如果你不关心在你的产出中保持秩序,而且你不会重复你的工作,你可以这样做:

a & (c-w .. c+w).to_a

Where c is the center of your interval and w is the interval s width. Using Array#& treats the arrays as sets so it will remove duplicates and is not guaranteed to preserver order.

问题回答

暂无回答




相关问题
Ruby parser in Java

The project I m doing is written in Java and parsers source code files. (Java src up to now). Now I d like to enable parsing Ruby code as well. Therefore I am looking for a parser in Java that parses ...

rails collection_select vs. select

collection_select and select Rails helpers: Which one should I use? I can t see a difference in both ways. Both helpers take a collection and generates options tags inside a select tag. Is there a ...

RubyCAS-Client question: Rails

I ve installed RubyCAS-Client version 2.1.0 as a plugin within a rails app. It s working, but I d like to remove the ?ticket= in the url. Is this possible?

Ordering a hash to xml: Rails

I m building an xml document from a hash. The xml attributes need to be in order. How can this be accomplished? hash.to_xml

multiple ruby extension modules under one directory

Can sources for discrete ruby extension modules live in the same directory, controlled by the same extconf.rb script? Background: I ve a project with two extension modules, foo.so and bar.so which ...

Text Editor for Ruby-on-Rails

guys which text editor is good for Rubyonrails? i m using Windows and i was using E-Texteditor but its not free n its expired now can anyone plese tell me any free texteditor? n which one is best an ...