Reiss Johnson
Reiss Johnson

Reputation: 1509

Removing unwanted characters from a string element in a ruby array

If I have the following array...

["a =>", "b => c", "c => f", "d => a", "e => b", "f =>"]

How might I get it to return...

["a", "b", "c", "c", "f", "d", "a", "e", "b", "f"]

I thought to iterate through with .map & use .tr or .gsub but I can never get it quite right...

Upvotes: 0

Views: 75

Answers (4)

Cary Swoveland
Cary Swoveland

Reputation: 110735

Depending on the possible form of the array and the desired return value, neither of which are made clear by the question, you could do the following.

arr = ["a_1 =>", "b 2 => cc3", "cc3 => f6", "d4 => a_1", "e5 => b 2", "f6 =>"]

arr.flat_map { |str| str.split /\s*=>\s*/ }
  #=> ["a_1", "b 2", "cc3", "cc3", "f6", "d4", "a_1", "e5", "b 2", "f6"] 

None of the other answers given to date return the same value for this array.

Upvotes: 0

Anthony
Anthony

Reputation: 15967

Assuming you just want the letters of the string:

arr = ["a =>", "b => c", "c => f", "d => a", "e => b", "f =>"]
arr.flat_map { |str| str.scan(/\w+/) }
=> ["a", "b", "c", "c", "f", "d", "a", "e", "b", "f"]

The regex \w says only match against a letter, number or underscore.

Upvotes: 4

tg_so
tg_so

Reputation: 496

This should do the trick:

arr = ["a =>", "b => c", "c => f", "d => a", "e => b", "f =>"]

arr.join(' ').scan(/\w/) 
OR
arr.join(' ').scan(/\w+/) 


=> ["a", "b", "c", "c", "f", "d", "a", "e", "b", "f"]

There is a nice website called Rubular (http://rubular.com/) where you can interactively test out variety of regular expressions against strings. It also lists "Regex quick reference" so you can learn about the regex you often see used in Ruby code.

Upvotes: 2

guitarman
guitarman

Reputation: 3310

["a =>", "b => c", "c => f", "d => a", "e => b", "f =>"].join.gsub(/=>| /, '').chars
# => ["a", "b", "c", "c", "f", "d", "a", "e", "b", "f"]

["a =>", "b => c", "c => f", "d => a", "e => b", "f =>"].join.gsub(/[^a-z]/, '').chars
# => ["a", "b", "c", "c", "f", "d", "a", "e", "b", "f"]

So I join the strings together (Array#join), replace chars you don't want with an empty string (String#gsub) and split the result string into its chars (String#chars).

Upvotes: 1

Related Questions