2

I need to do the following:

Write a function that takes a String and returns an Array/list with the length of each word added to each element

Examples:

add_length('apple ban') => ["apple 5", "ban 3"]  
add_length('you will win') => ["you 3", "will 4", "win 3"]

I can find the length of each word but my question is, how do I then create a new array appending the lengths to each respective element? I think i need to use map again, but I am not sure how...

This is how I have worked out the lengths:

def add_length(str)  
   str.split(" ").map(&:length).to_s
end

3 Answers 3

3

A little modification could make it work:

'apple ban'.split(" ").map {|w| w + ' ' + w.length.to_s}
# => ["apple 5", "ban 3"]
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! That worked, I was struggling with parameters
2

You can use string interpolation to avoid string concatination and to_s calls. Futhermore there is no need for the (" ") argument when you use split to split strings at whitespaces:

def add_length(words)
  words.split.map { |word| "#{word} #{word.length}" }
end

Comments

1

Use collect method

def add_length(str)

   str.split(" ").collect { |e| e + ' ' + e.length.to_s }

end

p add_length('apple ban')

Output:

["apple 5", "ban 3"]

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.