简体   繁体   中英

How to remove spaces from array using Ruby

Arr= ["abcd","1223"," 10829380","pqrs"]

I want to print array like this-

Arr=["abcd","1223","10829380","pqrs"]

You should follow naming patterns and not use Arr as this usually is used for class names.

arr = ["abcd","1223"," 10829380","pqrs"]
whitespace_removed_arr = arr.map { |item| item.strip }

map iterates the array of strings ( arr ) and builds a new array containing the return values of the block.

You can use the shorter version if you like:

arr = ["abcd","1223"," 10829380","pqrs"]
whitespace_removed_arr = arr.map(&:strip)

Please note that the solutions proposing strip! and map (inplace version iof strip ) will most likely not work or work in a confusing way since strip! (oddly enough) returns nil when the string was not changed.

"".strip => ""
"".strip! => nil
"".strip => ""
" ".strip! => ""

If you want to use the inplace variant of strip and modify the original array you will need to use each

arr.each(&:strip!)

each discards the return value from the block, and strip! modifies the string in place.

You could use Array#map! or Array.map . Array#map! changes the original array and Array#map returns a new array so the original array keeps unchanged. The map functions iterate about the array and execute the given block for each element in the array.

arr = ["abcd", "1223", " 10829380", "pqrs"]
arr.map!{ |el| el.strip }
arr
# => ["abcd", "1223", "10829380", "pqrs"]

# or

arr = ["abcd", "1223", " 10829380", "pqrs"]
arr.map{ |el| el.strip }
# => ["abcd", "1223", "10829380", "pqrs"]
arr
# => ["abcd", "1223", " 10829380", "pqrs"]

Btw: Variables in ruby begin with a lowercase letter or _ ( arr ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM