AshNaz87
AshNaz87

Reputation: 434

Outputting the values of an array given an array of indexes

Given an array such as words = ["hello", ", ", "world", "!"], I am required to manipulate the elements which are made up of letters, so I will get a string in the end such as "*hello*, *world*!"

I have managed to retrieve the indexes from the array which contain letters using words.map.with_index { |element, index| index if element[[/a-zA-Z+/]] == element }.compact, which are [0, 2].

How could I use these indexes in a function, such that I could manipulate the words?

Upvotes: 0

Views: 74

Answers (3)

Cary Swoveland
Cary Swoveland

Reputation: 110675

words.reject { |word| word.match?(/\p{^L}/) }.
      map { |word| "*%s*" % word }.
      join(', ')
  #=> "*hello*, *world*"

Upvotes: 0

Mark Thomas
Mark Thomas

Reputation: 37507

You don't need indexes for this. If you want to be able to put apply arbitrary logic to each array element, use map without indexes:

words.map{|w| w.gsub(/[a-zA-Z]+/,'*\0*')}.join

As others have pointed out, for the example you have given, you don't need to process the array at all, just join it into a string first. For example:

words.join.gsub(/[a-zA-Z]+/,'*\0*')

Upvotes: 2

Dyaniyal Wilson
Dyaniyal Wilson

Reputation: 1060

Try using Regexp, that would make your job easy. You can manipulate the elements after fetching it in an array

words = ["hello", ", ", "world", "!"]
array = []
words.each do |a|
  array << a if /\w/.match(a)
end

puts array

hello
world

Upvotes: 0

Related Questions