Created
May 11, 2018 12:43
-
-
Save Schwad/a6310e46025f38717dc208f2f6fad499 to your computer and use it in GitHub Desktop.
Description to self about certain ruby methods. For safe keeping really. If you've stumbled on here for some reason, hello!
This file contains hidden or 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
# Enumerable's Detect | |
# - returns first element for which block returns true and then stops. If none returns nil. | |
(1..100).detect { |i| i % 5 == 0 and i % 7 == 0 } #=> 35 | |
# Find All | |
(1..10).find_all { |i| i % 3 == 0 } #=> [3, 6, 9] | |
# Reject | |
(1..10).reject { |i| i % 3 == 0 } #=> [1, 2, 4, 5, 7, 8, 10] | |
# Select | |
# Same as find_all | |
[1,2,3,4,5].select { |num| num.even? } #=> [2, 4] | |
# Inject | |
# Reduce alias, with or without supplied default | |
%w{ cat sheep bear }.inject do |memo, word| | |
puts "memo: #{memo}" | |
puts "word: #{word}" | |
memo.length > word.length ? memo : word | |
end | |
# memo: cat | |
# word: sheep | |
# memo: sheep | |
# word: bear | |
%w{ cat sheep bear }.inject('huh') do |memo, word| | |
puts "memo: #{memo}" | |
puts "word: #{word}" | |
memo.length > word.length ? memo : word | |
end | |
# memo: huh | |
# word: cat | |
# memo: cat | |
# word: sheep | |
# memo: sheep | |
# word: bear | |
# Inspect | |
# String version of self, alias of 'to_s' | |
[ "a", "b", "c" ].to_s #=> "[\"a\", \"b\", \"c\"]" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment