Skip to content

Instantly share code, notes, and snippets.

@jordanhudgens
Last active February 4, 2022 09:51
Show Gist options
  • Save jordanhudgens/8033986 to your computer and use it in GitHub Desktop.
Save jordanhudgens/8033986 to your computer and use it in GitHub Desktop.
Functional Programming Exercises
### Generate an array of numbers, from 1 to 10:
(1..10).to_a
# => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
### Generate an array of letters from 'a' to 'g':
("a".."g").to_a
# ⇒ ["a", "b", "c", "d", "e", "f", "g"]
### Generate an array of double letters from 'aa' do 'gg':
("a".."g").to_a.map {|i| i * 2}
# ⇒ ["aa", "bb", "cc", "dd", "ee", "ff", "gg"]
### Generate an array of powers of 2, from 2^0 upto 2^10:
(1..10).to_a.map {|i| 2 ** i}
# ⇒ [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]
### Generate an array of even numbers from 2 to 10:
(1..10).to_a.select {|x| x.even?}
# ⇒ [2, 4, 6, 8, 10]
### Convert all strings into numbers:
["1", "23.0", "0", "4"].map { |x| x.to_i }
# ⇒ ["1", "23.0", "0", "4"] # ⇒ [1, 23, 0, 4]
### Choose first element of each subarray:
[[:a, 1], [:b, 2], [:c, 3], [:d, 4]].transpose[0]
# ⇒ [[:a, 1], [:b, 2], [:c, 3], [:d, 4]] # ⇒ [:a, :b, :c, :d]
# Choose second element from each subarray:
[[:a, 1], [:b, 2], [:c, 3], [:d, 4]].transpose[1]
# ⇒ [[:a, 1], [:b, 2], [:c, 3], [:d, 4]] # ⇒ [1, 2, 3, 4]
# Generate an array with subarrays, where each subarray has three elements, like so:
# I couldn't figure out how to get the output to be identical, I kept getting them in sequential order using:
(1..9).to_a.each_slice(3).to_a
# ⇒ [[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7]]
# Generate an array with hashes in it, which map numbers 1 through 10 with their squares:
# this was a trickier one, I kept trying variations of inject, but I couldn't get the results to match up...
Hash[*(1..10).map {|i| [i, i ** 2]}.flatten]
# ⇒ [{1⇒1}, {2⇒4}, {3⇒9}, {4⇒16}, {5⇒25}, {6⇒36}, {7⇒49}, {8⇒64}, {9⇒81}, {10⇒100}]
# Generate an array of dates in the given format for the last 7 days (obviously the dates will differ in this case, as the code should depend on the current date):
# I have this so far: ((DateTime.now - 7.days)..DateTime.now) - but I'm not sure how to get it to sequence and then convert it to an array, the usual methods throw errors.
# ⇒ ["2012-11-13", "2012-11-14", "2012-11-15", "2012-11-16", "2012-11-17", "2012-11-18", "2012-11-19"]
# Generate an array for the last 3 days, each element being a hash with date string and count = 1:
# ⇒ [{:date⇒"2012-11-17", :count⇒1}, {:date⇒"2012-11-18", :count⇒1}, {:date⇒"2012-11-19", :count⇒1}]
# Combine elements of an array into a string with a comma:
['one', 'two', 'three'].join(",")
#['one', 'two', 'three'] # ⇒ "one,two,three"
# Combine elements of a hash into a string in a URL-params-style:
# couldn't get this one to work with that syntax, I got it to work when the hash is structured like this:
# {:a => "foo", :b => "bar"}.map{|a,b| "#{a}=#{b}"}.join('&')
#{a: 'foo', b: 'bar'} # ⇒ "a=foo&b=bar"
# Remove nils from an array:
[1, 2, nil, 3, nil, 4, 5].compact
#[1, 2, nil, 3, nil, 4, 5] # ⇒ [1, 2, 3, 4, 5]
# Choose only even numbers from an array:
[1, 3, 4, 7, 8, 9, 123, 245].select { |x| x.even? }
# or
[1, 3, 4, 7, 8, 9, 123, 245].delete_if &:odd?
#[1, 3, 4, 7, 8, 9, 123, 245] # ⇒ [4, 8]
# Choose from an array strings longer than 10 characters only:
%w(A dynamic, open source programming language with a focus on simplicity and productivity).select { |x| x.length > 10 }
#%w(A dynamic, open source programming language with a focus on simplicity and productivity) # ⇒ ["programming", "productivity"]
# Choose the vowels from a string array using regular expressions
%w(a b c d e f g).select { |v| v =~ /[aeiou]/ }
#=> ["a", "e"]
# Remove strings that start with "system.":
["system.users", "system.indexes", "users", "transactions"].delete_if {|x| x =~ /system./ }
#["system.users", "system.indexes", "users", "transactions"] # ⇒ ["users", "transactions"]
# Find the lowest number in an array:
[4, 2, 70, 23].min
#[4, 2, 70, 23] # ⇒ 2
# Find the shortest string in an array:
["abc", "x", "foobar"].min{|a,b| a.size <=> b.size }
#["abc", "x", "foobar"] # ⇒ "x"
# Find the newest (highest) date:
# I thought min/max would work on this but it didn't, I'm not sure.
#['2012-04-03', '2012-2-1', '2012-10-11'] # ⇒ '2012-10-11'
# Calculate a sum of all numbers in an array:
[1, 2, 3, 4].inject{|sum,x| sum + x }
#[1, 2, 3, 4] # ⇒ 10
# Multiply all numbers in an array together:
[1, 2, 3, 4].inject{|sum,x| sum * x }
#[1, 2, 3, 4] # ⇒ 24
# Covert an array of numbers into a hash that has the number as the key and value as its integer value:
Hash[[1, 2.1, 3.33, 0.9].map {|x| [x,x.to_i]}]
#[1, 2.1, 3.33, 0.9] # ⇒ {1⇒1, 2.1⇒2, 3.33⇒3, 0.9⇒0}
# Convert an array of strings into a hash that has the string as the key and value as the string's length:
Hash[%w(A dynamic open source programming language).map {|x| [x,x.length]}]
#%w(A dynamic open source programming language) # ⇒ {"A"⇒1, "dynamic"⇒7, "open"⇒4, "source"⇒6, "programming"⇒11, "language"⇒8}
# Generate an array of the first 5 letter of the alphabet, along with their index:
#[[1, "a"], [2, "b"], [3, "c"], [4, "d"], [5, "e"]]
# Divide an array of numbers into two arrays: one with even numbers, and other with odd numbers:
#[1, 2, 4, 5, 6, 9, 11, 12] # ⇒ [[2, 4, 6, 12], [1, 5, 9, 11]]
[1, 2, 4, 5, 6, 9, 11, 12].partition {|x| x.even?}
# Sort an array of numbers:
#[4, 2, 5, 7] # ⇒ [2, 4, 5, 7]
[4, 2, 5, 7].sort
# Sort an array of strings by their length:
# %w(A dynamic open source programming language) # ⇒ ["A", "open", "source", "dynamic", "language", "programming"]
%w(A dynamic open source programming language).sort_by {|x| x.length}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment