· 9 years ago · Oct 11, 2016, 09:40 AM
1# Use of ARGV
2beer_song(ARGV[0].to_i) # use ARGV[0], ARGV[1], ... in program
3ruby beer_song.rb 32 "test" # will pass 32 as ARGV[0], "test" as ARVV[1], etc.
4
5# Pry byebug
6require 'pry byebug'
7binding.pry #next, step to enter method, !!! to exit, continue? and don't forget help
8
9# Argument Error
10fail ArgumentError, "#{number} should be greater than 1" if number < 1
11raise ArgumentError, "error message string"
12
13# !! : transforms truthy into true and falsy into false
14!!hash[key] # if hash[key] is different from nil (= returns a value), transforms to true. Transforms to false otherwise
15
16# .empty? method and use of delete_at
17old = array.dup
18until old.empty?
19 old.delete_at(n)
20end
21
22# Regexp non-capturing group
23([^\.@]+)(?:\.([^@]+))?@([^@]+) # (?:xxx)
24
25# Clever way of splitting on non-word characters with Regex
26line.chomp.downcase.split(/\W+/)
27
28# Clever return trip from Hash to Array to Hash + first number_of_world elements
29Hash[counter.sort_by { |_, v| -v }[0..(number_of_word - 1)]]
30
31# Don't forget the power of reduce
32File.open(stop_words_filename, "r").reduce(Array.new) do |stop_words, line|
33 stop_words << line.chomp
34end
35
36# Regex domain definition and use, group_by method from Array to Hash
37MAIL_REGEX = /@(?<domain>[^\.]+)\./
38
39def group_mails(emails)
40 emails.select { |email| MAIL_REGEX.match(email) }
41 .group_by { |email| MAIL_REGEX.match(email)[:domain] }
42end
43
44def provider?(email, provider)
45 match = MAIL_REGEX.match(email)
46 match[:domain] == provider
47end
48
49# Resolve address with recursive method on hash | use of double-pipe ||
50STRINGS = {
51 home: {
52 intro: {
53 en: 'Welcome on Le Wagon'
54 }
55 }
56}
57
58def translation(a_string, a_language = :en)
59 keys = a_string.split(".")
60 translation = STRINGS
61 keys.each do |key|
62 translation = translation[key.to_sym]
63 return "" if translation.nil?
64 end
65 translation[a_language.to_sym] || translation[:en]
66end
67
68# % what is that?
69JOKES = {
70 "live.com" => "%s, aren't you born before 1973?",
71 "gmail.com" => "%s, you're an average but modern person",
72 "lewagon.org" => "Well done %s, you're skilled and capable"
73}
74
75JOKES[email_domain] % full_name