iterator inside string

A

akbarhome

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.
 
R

Robert Klemme

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
 
F

Farrel Lifson

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
 
L

Louis J Scoras

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"
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,141
Latest member
BlissKeto
Top