Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save vaichidrewar/7177033 to your computer and use it in GitHub Desktop.
Save vaichidrewar/7177033 to your computer and use it in GitHub Desktop.
how to use collect or map or select or each or inject or reject Or when to use each vs collect vs map vs select vs each vs inject vs reject
map and collect are same http://stackoverflow.com/questions/5254732/difference-between-map-and-collect-in-ruby
http://matthewcarriere.com/2008/06/23/using-select-reject-collect-inject-and-detect/
1. Use select or reject if you need to select or reject items based on a condition.
2. Use collect if you need to build an array of the results from logic in the block.
3. Use inject if you need to accumulate, total, or concatenate array values together.
4. Use detect if you need to find an item in an array.
Building a list of items from the array using select
a = [1,2,3,4]
a.select {|n| n > 2}
This will return the last two elements in the array: 3 and 4. Why? Because 3 and 4 are both greater than 2, which was the logic we placed in the block. If the logic returns TRUE, then it adds the item to a new array. ‘reject’ adds items to a new array if the logic returns FALSE.
a = [1,2,3,4]
a.collect {|n| n*n}
This returns a new array with each item in our array squared.
Total the items in an array using inject
The main difference between select and inject is that inject gives you another variable for use in the block. This variable, referred to as the accumulator, is used to store the running total or concatenation of each iteration.
a = [1,2,3,4]
a.inject {|acc,n| acc + n}
This will return 10. The total value of all the elements in our array.
You can also use a parameter with the inject call to determine what the default value for the accumulator is:
a = [1,2,3,4]
a.inject(10) {|acc,n| acc + n}
In this example the result is 20 because we assigned the accumulator an initial value of 10.
Find an item in the array using detect
a = [1,2,3,4]
a.detect {|n| n == 3}
This returns 3. The value we were looking for. If the value had not been found, then the iterator returns nil.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment