Skip to content

Instantly share code, notes, and snippets.

@louim
Created February 23, 2013 17:04
Show Gist options
  • Select an option

  • Save louim/5020463 to your computer and use it in GitHub Desktop.

Select an option

Save louim/5020463 to your computer and use it in GitHub Desktop.
#take a string and split it in hash, based on letter frequency
#take a string and split it in hash, based on letter frequency
class NameToHash
def initialize(name = "Louis-Michel")
@name = name.downcase
name_convert
end
def name_convert
hash = Hash.new
@name.each_char do |lettre|
if hash.has_key?(lettre)
hash[lettre] += 1
else
hash[lettre] = 1
end
end
puts hash
end
end
@remi
Copy link
Copy Markdown

remi commented Feb 23, 2013

  1. Tu pourrais profiter du constructeur de Hash qui prend un argument optionnel. Cet argument sera retourné si on appelle Hash#[] avec une clé inconnue

    a = Hash.new("what")
    a["hello"] # => "what"
    a["hola"] = "yep"
    a["hola"] # => # "yep"
    a["bonjour"] # => "what"
  2. Regarde Enumerable#inject, ça pourrait t’aider à refactorer ton code. C’est complexe, mais très puissant 😄

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment