Posted By

neil on 07/25/08


Tagged

sort array first


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

webstic


Array hacks


 / Published in: Ruby
 

  1. class Array
  2.  
  3. # order the elements of this array by the values of the specified attribute of
  4. # each element
  5. #
  6. def sort_by_attribute! atb
  7.  
  8. sort! {|a,b| a.send(atb) <=> b.send(atb)}
  9. end
  10.  
  11.  
  12. # provides the first element of this array for which the block provides "true"
  13. #
  14. def first_where
  15.  
  16. each do |element|
  17.  
  18. return element if yield element
  19. end
  20.  
  21. nil
  22. end
  23.  
  24.  
  25. def index_of_first_where
  26.  
  27. each_with_index do |element,i|
  28.  
  29. return i if yield element
  30. end
  31. end
  32.  
  33. end

Report this snippet  

You need to login to post a comment.