2015-04-22 183 views
1

在我的應用程序中,我需要從條件和前一個數組中選擇元素。我使用each_cons方法,所以我的代碼如下所示:從數組中選擇兩個元素

range_to = 2500 

points = [ 
    {alti: 3000, time: 1}, 
    {alti: 2000, time: 2}, 
    ... 
] 

points.each_cons(2) do |pair| 
    if pair.last[:alti] <= range_to 
    new_point = Interpolation.find_between(pair.first, pair.last, range_to) 
    end 
    break if new_point 
end 

Interpolation.find_between使得在論證兩者之間鋪設,像插和回報點:

{alti: 2500, time 1.5} 

是否有更多的權利/優雅的方法?

+1

鑑於您正在枚舉數組中的每個相鄰對,'each_cons'是該作業的正確工具。 –

+3

'@ points','@ range_to','Interpolation','find_between'是什麼? – sawa

+0

@sawa,我改進了我的問題。 –

回答

0

隨着Pepegasca answer我來到這個解決方案:

pair = 
    points.each_cons(2).detect do |pair| 
    range_to.between? pair.last[:alti], pair.first[:alti] 
    end 

return nil unless pair 

Interpolation.find_between(pair.first, pair.last, range_to) 

我認爲這是簡單,清晰,並按照紅寶石風格指南。

points.each_cons(2)無給定的回報Enumerator,則detect首先在塊狀態下給出。然後檢查是否成功,如果是 - 功能Interpolation.find_between完成其工作並返回值。

1

您可以使用類似:

selected_points = points.each_cons(2).select{|p| p.last[:alti] <= range_to}.first 
selected_points && new_point = Interpolation.find_between(selected_points.first, selected_points.last, range_to) 
+0

像你的解決方案,但更好地使用'detect'而不是'select {} .first'。 –

0

不在這裏肯定each_cons讓事情更清晰。爲什麼不這樣做?

upper = points.find_index{|point| point[:alti] <= range } 
lower = upper - 1 
new_point = Interpolation.find_between(points[lower], points[upper], range_to) 
+0

它會造成附加條件。例如,如果upper將是第一個元素。 –