Skip to content

Instantly share code, notes, and snippets.

@theoretick
Last active August 29, 2015 14:24
Show Gist options
  • Save theoretick/cb359c98c718ef5aa269 to your computer and use it in GitHub Desktop.
Save theoretick/cb359c98c718ef5aa269 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
# generate a growing value for each letter (in this case its place in the alphabet, e.g. j == 9)
# for each character in the string take the index position of the character (where it is in the
# string) and save that value + 1 with the character. Indexes always start w/ zero, that's why
# we need to add 1. `map` means for each value we produce, save them all and return them together.
letters_with_numeric_values = 'abcdefghijklmnopqrstuvwxyz'.chars.each_with_index.map do |letter, i|
[letter, i+1]
end
# last step we generated an array of arrays, this makes it a hash for convenience. Arrays are
# collections of values, hashes are collections of keys AND values, so they are easier to
# reference the number by the letter.
#
# previously:
# [
# [a, 1],
# [b, 2],
# [c, 3],
# ...
# ]
#
# afterwards:
# {
# a: 3,
# b: 4,
# c: 5,
# ...
# }
lookup_hash = Hash[letters_with_numeric_values]
# ARGV contains whatever argument you pass to the script, so the word we are passing in.
# downcase means we want all letters in their lowercase style, to standardize.
word = ARGV.first.downcase
# iterate over each character in the word, look up its value in the lookup_hash, and sum them
total = 0
word.chars.each do |character|
total = total + lookup_hash[character]
end
# print it. `to_s` converts an integer to a string to print it correctly.
puts "total: " + total.to_s
~$ ./gematria.rb abc
total: 6
~$ ./gematria.rb seth
total: 52
~$ ./gematria.rb s
total: 19
~$ ./gematria.rb e
total: 5
~$ ./gematria.rb t
total: 20
~$ ./gematria.rb h
total: 8
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment