[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

iterator inside string

akbarhome

10/19/2006 1:29:00 PM

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.

3 Answers

Robert Klemme

10/19/2006 1:32:00 PM

0

On 19.10.2006 15:29, akbarhome wrote:
> 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.
>
use #map instead of #each

robert

Farrel Lifson

10/19/2006 1:38:00 PM

0

On 19/10/06, akbarhome <akbarhome@gmail.com> wrote:
> 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.

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

Farrel

Louis J Scoras

10/19/2006 1:42:00 PM

0

On 10/19/06, akbarhome <akbarhome@gmail.com> 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"


--
Lou.