سؤال

I have an array that contains three words

three_words = ["if", "the", "printed"]

The words are in an instance method inside of a class, and I want it so that when I call the instance method on a test it prints out like :

"if the printed" 

I tried adding the following to the method at the end, but when I call the instance method on a string it still returns ["if", "the", "printed"]

three_mcwords.each do |word|
  word + " " 
end
هل كانت مفيدة؟

المحلول

You need to look for the method Array#join, as three_mcwords.join(" "). But you called Array#each, which return the receiver (as per the MRI implementation), on which you called the method #each.

You called three_mcwords.each do |word|... See here the receiver is three_mcwords, which holds the reference of the array ["if", "the", "printed"], thus when each block competed, you got the array ["if", "the", "printed"] back.

Example :

['foo', 'bar'].each { |str| "hi" + str } # => ["foo", "bar"]
['foo', 'bar'].join(" ") # => "foo bar"

Both are working as they were implemented in MRI.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top