0

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?

8
  • Unclear. Why do you collect the indices instead of directly collecting or modifying the words? Commented Dec 15, 2017 at 17:42
  • 2
    I think you are over thinking the problem a bit. Since the desired end result is a string it would make the most sense in this case to convert it to a String and then manipulate it using the methods String provides words.join.gsub(/\w+/) {|m| "*#{m}*"} Commented Dec 15, 2017 at 17:43
  • 2
    @engineersmnky Or slightly shorter using a variation of an answer Stefan provided here words.join.gsub(/\w+/,'*\0*'). Commented Dec 15, 2017 at 17:51
  • 2
    @SagarPandya Nah, words.join.gsub(/\b/, '*'). Commented Dec 15, 2017 at 18:22
  • @SagarPandya What does the '*\0*' do exactly? Commented Dec 16, 2017 at 10:20

3 Answers 3

2

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*')
Sign up to request clarification or add additional context in comments.

2 Comments

Well, I'd say it fails for example for ["hello", ", ", "42", "!"] which it turns into "*hello*, *42*!", surrounding the number with asterisks. (That's one reason I didn't post it as answer myself but just as comment-reply to the previous comments)
Good point, I've changed it to use OP's regex. Hey, digits are word characters according to regex :)
0

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

1 Comment

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.