Iterator inside string

Hi,

This is the code:
a = [ ‘a’, ‘b’ ]
b = 2
stringbla = “home #{ a.each {|i| i * b } } work”
puts stringbla

output:
home ab work

How do I modifiy the iterator so the output will be:
home aabb work

Thank you.

On 19.10.2006 15:29, akbarhome wrote:

How do I modifiy the iterator so the output will be:
home aabb work

Thank you.

use #map instead of #each

robert

On 19/10/06, akbarhome [email protected] wrote:

How do I modifiy the iterator so the output will be:
home aabb work

Thank you.

stringbla = “home #{ a.map {|i| i * b } } work”

Farrel

On 10/19/06, akbarhome [email protected] wrote:

How do I modifiy the iterator so the output will be:
home aabb work

Thank you.

The to_s method is going to be called on whatever value the #{ … }
evaluates to. That’s why you are getting “ab”

a.each {|i| i * b}.to_s # => "ab"

if you use collect rather than each, you’ll get

x = a.collect {|i| i * b}  # => ["aa", "bb"]
x.to_s                        # => "aabb"

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs