Created
February 24, 2009 10:52
-
-
Save fdutey/69510 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
posts = Post.all | |
#renvoie true si ma collection a plusieurs (> 1) élément répondant à la condition passée sous forme de bloc | |
posts.many?(&:published?) #=> true | |
#renvoie true si aucun élément de ma collection ne répond à la condition passée sous forme de bloc | |
posts.none?(&:published?) #=> false | |
#effectue la somme des valeurs renvoyées successivement par un bloc executé sur chaque élément de ma collection | |
posts.sum(&:comments_count) #=> 10 | |
items_count = Tag.all.sum{ |t| t.posts_count + t.articles_count } #=> 100 | |
#En clean | |
class Tag | |
def items_count | |
posts_count + articles_count | |
end | |
end | |
Tag.all.sum(&:items_count) #=> 100 | |
#Transforme une collection en hash, le block passé en paramètre décrit comment sera créée la clef | |
posts.index_by(&:id) #=> { 1 => #<Post ...>, 2 => #<Post ...>, 3 => #<Post ...> } | |
#Si plusieurs objets génèrent la meme clef, alors le dernier à la générer sera celui présent dans le hash | |
posts.index_by(&:published?) #=> { true => #<Post ...>, false => #<Post ...> } | |
#Permet de regrouper des valeurs dans des Set selon un critère | |
posts.group_by(&:published?) #=> [[true, [#<Post ...>, #<Post ...>]], [false, [#<Post ...>]]] | |
posts.group_by(&:published?).to_hash #=> { true => [#<Post ...>, #<Post ...>], false => [#<Post ...>] } | |
#Permet de faire du one line | |
indexed_by_title_posts = posts.each_with_object({}){ |post, memo| memo[post.title] = post } | |
#plutot que | |
indexed_by_title_posts = {} | |
posts.each{ |post| index_by_title_posts[post.title] = post } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment