Friday, 15 May 2015

arrays - block inside interpolation with ruby -



arrays - block inside interpolation with ruby -

i'm writing simple programme asks user input array , spits out array , average. easy , had no issues it.

in end came with: (in illustration i'll utilize random array instead of code user input)

array = [1,2,3] sum = array.inject(:+) average = sum.to_f/array.length puts "the numbers entered in array were: #{array.join(" ")}" puts "the average of numbers are: #{average}"

the output expected , gives me:

the numbers entered in array were: 1 2 3 averages of numbers are: 2.0

however, when first trying code trying real slick easy assignment , tried doing interpolation within of interpolation. utilized code:

for 4th line in above code used:

puts "the numbers entered in array were: #{array.each{|num| print "#{num} "}}"

which outputted:

1 2 3 numbers entered in array were: [1, 2, 3]

so thought there might have been issue doing interpolation within block within of interpolation. ran next code test block within interpolation.

puts "the numbers entered in array were: #{array.each{|num| print num}}"

which outputted:

123the numbers entered in array were: [1, 2, 3]

can explain me why proc executed within of interpolation first, printed , puts happens. in addition, why did puts array in array.inspect form when never called .inspect on array.

the question want answered

when utilize variable interpolation, value interpolate going resolve before original string.

in case, array.each doing it's thing , printing out "1" "2" , "3". returns original array of [1, 2, 3]

output> 123 # note new line because used print

now interpolation resolved, rest of puts finishes , uses returned value of [1, 2, 3] , prints:

output> numbers entered in array were: [1, 2, 3]\n

to final output of:

output> 123the numbers entered in array were: [1, 2, 3]\n the question wants reply :)

http://www.ruby-doc.org/core-2.1.4/array.html#method-i-each

when calling array.each block, homecoming self.

this "bad" in case, because don't want self returned. homecoming same thing, original array.

puts "the numbers entered in array were: #{array.each{|num| num*2}}" numbers entered in array were: [1, 2, 3] # wat?

as sergio tulentsev said, utilize .map , .join

puts "the numbers entered in array were: #{array.map{|num| num*2}.join(' ')}" numbers entered in array were: 2 4 6

ruby arrays codeblocks string-interpolation

No comments:

Post a Comment