我有待辦事項的數組[Todo1, Todo2, Todo3]
如何判斷Ruby on Rails 3中的對象數組的索引?
每個對象都有一個屬性,:done_date
我需要找對象的第一實例,其中:done_date => null
然後,我需要知道什麼索引呢是todos[N]
所以我可以找到之前todos[N-1]
我該怎麼做?
我有待辦事項的數組[Todo1, Todo2, Todo3]
如何判斷Ruby on Rails 3中的對象數組的索引?
每個對象都有一個屬性,:done_date
我需要找對象的第一實例,其中:done_date => null
然後,我需要知道什麼索引呢是todos[N]
所以我可以找到之前todos[N-1]
我該怎麼做?
你可以試着用稍微不同的方式去做。利用Ruby的Enumerable#take_while
的:
# assuming 'todos' holds your todo objects
todos.take_while { |todo| todo.done_date != nil }.last
這將讓來自todos
所有待辦事項對象,直到它看到一個零done_date
,然後抓住最後一個。您將在第一個零done_date
之前獲得最後的待辦事項。
所以,如果你有
todos = [todo1, todo2, todo3, todo4_with_null_done_date]
代碼上面的例子將返回todo3
。
也就是說,如果你真的尋找的東西,利用陣列的indicies的,你可以嘗試這樣的事情還有:
first_nil_index = todos.find_index { |todo| todo.done_date.nil? }
todos[first_nil_index - 1]
嗯,這很不錯,我喜歡這個。 – Angela
我不明白_first_什麼定義。在SQL(Set Query Language)中,沒有定義的順序。你會以隨機順序得到它們。如果訂單已經定義,那麼你有數組,使用:'ind = array.find_index {| t | t.done_date == nil}'。 – mliebelt
對,這是下一部分 - 我需要按original_date對它進行排序,我該怎麼做? – Angela
'array.sort {| a,b | a.original_date <=> b.original_date}'? – mliebelt