How can I uppercase each element of an array?

前端 未结 3 1393
不思量自难忘°
不思量自难忘° 2020-12-30 21:17

How can I turn an array of elements into uppercase? Expected output would be:

[\"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\"]  
=> [\"M         


        
相关标签:
3条回答
  • 2020-12-30 22:07

    This should work:

    Day.weekday.map(&:name).map(&:upcase)
    

    Or, if you want to save some CPU cycles

    Day.weekday.map{|wd| wd.name.upcase}
    
    0 讨论(0)
  • 2020-12-30 22:11

    Return a New Array

    If you want to return an uppercased array, use #map:

    array = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
    
    # Return the uppercased version.
    array.map(&:upcase)
    => ["MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY"]
    
    # Return the original, unmodified array.
    array
    => ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
    

    As you can see, the original array is not modified, but you can use the uppercased return value from #map anywhere you can use an expression.

    Update Array in Place

    If you want to uppercase the array in-place, use #map! instead:

    array = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
    array.map!(&:upcase)
    array
    => ["MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY"]
    
    0 讨论(0)
  • 2020-12-30 22:13

    In your example, replace 'each' with 'map'.

    While 'each' iterates through your array, it doesn't create a new array containing the values returned by the block.

    0 讨论(0)
提交回复
热议问题