Use the .map Method To Iterate And To Return Modified Object

by

in

Developers have to understand the difference between .map and .each methods. When using these functions try to choose the appropriate method based on the situations.
For example, If you want to return the vowels array in the capital letter then use .map method,

Don’ts

vowels = [‘a’, ‘e’, ‘i’, ‘o’, ‘u’] new_vowels = [] vowels = vowels.each { |vowel| new_vowels << vowel.upcase } puts new_vowels -> [‘A’, ‘E’, ‘I’, ‘O’, ‘U’]

Do’s

vowels = [‘a’, ‘e’, ‘i’, ‘o’, ‘u’] new_vowels = vowels.map { |vowel| vowel.upcase } puts new_vowels -> [‘A’, ‘E’, ‘I’, ‘O’, ‘U’]

Related: Top Companies That Use Ruby on Rails


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *