1

All,

New to Ruby and playing around. Here's my array:

fruits = ["banana", "apple", "pear", "orange"]

I accumulated like this:

longest_sentence = fruits.inject("banana") do |memo, fruit|
  if memo == fruits[0]
    puts "I like " + fruit + "s and "
  else
    puts fruit + "s and "
  end
end

As expected, it gave me this:

I like bananas and 
apples and 
pears and 
oranges and 
=> nil

Here's are my two questions:

  1. How would you condense this code into a single line (i.e.no code block)?
  2. How would you display the results as a single string (i.e. "I like bananas and apples and pears and oranges and" without the awkward line returns)?

Thanks!

1
  • 1
    "I like apples and oranges and" is invalid english :) Commented Feb 14, 2016 at 21:20

3 Answers 3

2

The argument you pass to reduce should be the initial value you want memo to have. In this case, it looks like you want it to be "I like". Additionally, don't do puts inside the block. reduce (like map et al) is for "building" objects. Once you're done, then print the string you built:

sentence = fruits.inject("I like") do |memo, fruit|
  memo << " #{fruit}s and"
end

puts sentence
# => I like bananas and apples and pears and oranges and
Sign up to request clarification or add additional context in comments.

Comments

0

You don't need inject/reduce for this.

fruits = ["banana", "apple", "pear", "orange"]
puts "I like " + fruits.map{|f| f + 's'}.join(' and ') 
# >> I like bananas and apples and pears and oranges

Comments

0
puts "I like #{fruits.join('s and ')}s" 
  #-> I like bananas and apples and pears and oranges

or

puts "I like %ss" % fruits.join("s and ")

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.