Skip to content

Instantly share code, notes, and snippets.

@Papillard
Created July 13, 2017 09:08
Show Gist options
  • Save Papillard/bb61560a235653ca05f2f9bf3fe9d703 to your computer and use it in GitHub Desktop.
Save Papillard/bb61560a235653ca05f2f9bf3fe9d703 to your computer and use it in GitHub Desktop.
Playing with iterators
musicians = ["Jimi Hendrix", "Bob Dylan", "Michael Jackson", "Barry White", "Justin Bieber"]
# each: to iterate on elemens
musicians.each do |musician|
puts "Hello #{musician}"
end
# each_with_index: iterate on element + index
musicians.each_with_index do |musician, index|
puts "Musician N#{index} - #{musician}"
end
# map: transform an array into a new one
upcased_musicians = musicians.map do |musician|
musician.upcase
end
first_name_musicians = musicians.map do |musician|
musician.split.first
end
p first_name_musicians
# count elements verifying a condition
j_count = musicians.count do |musician|
musician.start_with? "J"
end
p j_count
# select elements verifying a condition
j_musicians = musicians.select do |musician|
musician.start_with? "J"
end
p j_musicians
# select elements verifying a condition
musicians_with_colleagues = musicians.select do |musician|
first_letter = musician[0]
musicians.count {|musician| musician.start_with? first_letter} > 1
end
p musicians_with_colleagues
# # reject elements verifying a condition
non_j_musicians = musicians.reject do |musician|
musician.start_with? "J"
end
p non_j_musicians
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment