Last active
January 22, 2024 16:43
-
-
Save profh/fc96546bb0e3da96a8ef5cd7c7d00e17 to your computer and use it in GitHub Desktop.
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
### A SIMPLE EXAMPLE OF BLOCKS | |
numbers = [1, 2, 3, 4, 5] | |
# .each iterates through an array or hash and performs an anonymous function on it | |
numbers.each { |n| puts "The square of #{n} is #{n**2}" } | |
# note also the string interpolation with the #{} | |
# note that numbers is unchanged | |
p numbers | |
puts "\n\n--------\n\n" | |
# another way of representing a block via do..end | |
numbers.each do |n| | |
puts n**2 | |
end | |
p numbers | |
puts "\n\n--------\n\n" | |
# .map interates through the array, performs the anon function and returns the result to a new array | |
squares = numbers.map { |n| n**2 } | |
# original array unchanged | |
p numbers | |
# a new array with squared values | |
p squares | |
puts "\n\n--------\n\n" | |
# .select filters an array or hash and returns only those values for which the anon function returns true | |
evens = numbers.select { |n| n%2 == 0 } | |
p numbers # original still unchanged | |
p evens | |
puts "\n\n--------\n\n" | |
# %w makes a special word array w/o quote marks and delimited by spaces | |
colors = %w[blue red orange green purple yellow] | |
p colors | |
p colors.sort | |
# here we are making a hash with some syntactic sugar | |
color_enum = {blue: 0, red: 2, orange: 4, green: 1, purple: 3, yellow: 5} | |
# this is how Ruby sees the array | |
p color_enum | |
# can sort_by any criterion specified in the block; in this case, by values | |
p color_enum.sort_by { |k,v| v } | |
# checking to see what's included; separating the hash into keys and values arrays | |
puts color_enum.keys.include? :blue | |
puts color_enum.values.include? 7 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment