Comparison of a simple, idiomatic ruby program to a similar go program.
To run the ruby program: ruby mammals.rb
To run the go program: go run mammals.go
Comparison of a simple, idiomatic ruby program to a similar go program.
To run the ruby program: ruby mammals.rb
To run the go program: go run mammals.go
| package main | |
| import ( | |
| "fmt" | |
| "strings" | |
| ) | |
| type Mammal struct { | |
| name string | |
| group string | |
| } | |
| var mammals = []Mammal{ | |
| Mammal{"Baboon", "Primates"}, | |
| Mammal{"Dingo", "Carnivora"}, | |
| Mammal{"Bison", "Artiodactyla"}, | |
| Mammal{"Gerbil", "Rodentia"}, | |
| Mammal{"Bear", "Carnivora"}, | |
| Mammal{"Chimpanzee", "Primates"}, | |
| Mammal{"Deer", "Artiodactyla"}, | |
| Mammal{"Fox", "Carnivora"}, | |
| Mammal{"Hamster", "Rodentia"}, | |
| Mammal{"Jaguar", "Carnivora"}, | |
| } | |
| func main() { | |
| groupedMammals := make(map[string][]string) | |
| for _, mammal := range mammals { | |
| _, ok := groupedMammals[mammal.group] | |
| if !ok { | |
| groupedMammals[mammal.group] = make([]string, 0) | |
| } | |
| groupedMammals[mammal.group] = append(groupedMammals[mammal.group], mammal.name) | |
| } | |
| for group, animalNames := range groupedMammals { | |
| fmt.Printf("%s: %s\n", group, strings.Join(animalNames, ", ")) | |
| } | |
| } | 
| class Mammal | |
| attr_accessor :name, :group | |
| def initialize(name, group) | |
| self.name = name | |
| self.group = group | |
| end | |
| end | |
| mammals = [ | |
| Mammal.new('Baboon', 'Primates'), | |
| Mammal.new('Dingo', 'Carnivora'), | |
| Mammal.new('Bison', 'Artiodactyla'), | |
| Mammal.new('Gerbil', 'Rodentia'), | |
| Mammal.new('Bear', 'Carnivora'), | |
| Mammal.new('Chimpanzee', 'Primates'), | |
| Mammal.new('Deer', 'Artiodactyla'), | |
| Mammal.new('Fox', 'Carnivora'), | |
| Mammal.new('Hamster', 'Rodentia'), | |
| Mammal.new('Jaguar', 'Carnivora') | |
| ] | |
| grouped_mammals = {} | |
| mammals.each do |mammal| | |
| grouped_mammals[mammal.group] ||= [] | |
| grouped_mammals[mammal.group] << mammal.name | |
| end | |
| grouped_mammals.each do |group, mammal_names| | |
| puts "#{group}: #{mammal_names.join(', ')}" | |
| end |