So I have another boy on the way and I was trying to think up of names so I created a ruby script to pick a
random name out of a file beginning with a letter that you provide as an argument. So you’d call the script like this:
12
ruby boy_name.rb s=> Sylen
1234567891011
# using ruby 1.8.7ifARGV.empty?puts"USAGE: ruby boy_name.rb <letter>"exitendfile=File.open("boy_names.txt")names=file.lines.to_a.group_by{|name|name[0,1]}selected_names=names[ARGV[0].capitalize]putsselected_names[rand(selected_names.size)]
What’s cool about it is this line
1
names=file.lines.to_a.group_by{|name|name[0,1]}
Enumberable#group_by will group elements in an array by the result of the block passed in. In this case, we’re grouping by
the first letter.