Forum: Ruby how to write a array into a string

Posted by Edward QU (autogyro)
on 2012-09-15 05:57
Hello all
I have a array, this is a information queue,I want to send it as the
content of email line by line.

my script is as the following:

str=msg_queue.each_with_index do |msg, index| puts "#{index} :
#{msg}!"end

sendemail(from,to,titel,str)

but, in the email, i got the content is a array format,

["[2012-09-15,Sat,11:53:41] No this month log file, created
itddfafafad", "[2012-09-15,Sat,11:53:41] No this month leeog fil",
"[2012-09-15,Sat,11:53:41] No this month leeeog fil",
"[2012-09-15,Sat,11:53:41]

what i wanted is as the following:


0 : [2012-09-15,Sat,11:53:41] No this month log file, created
itddfafafad!
1 : [2012-09-15,Sat,11:53:41] No this month leeog fil!
2 : [2012-09-15,Sat,11:53:41] No this month leeeog fil!
3 : [2012-09-15,Sat,11:53:41] No this month
lodd666666666666666666ddddgeee fil!

any help would be very appreciated.

Regards
Edward.
Posted by 7stud -- (7stud)
on 2012-09-15 06:14
arr = ['a', 'b', 'c']
str = arr.each_with_index do |num, i|
  puts "#{i} => #{num}"
end

--output:--
0 => a
1 => b
2 => c
["a", "b", "c"]

You see, each_with_index() is a method call, and it has a return value, 
and the return value is the array you started with.  puts() is also a 
method and it sends text to your screen.  Displaying text on your screen 
does not save the text anywhere.
Posted by 7stud -- (7stud)
on 2012-09-15 06:18
arr = ['a', 'b', 'c']
result_str = ""

arr.each_with_index do |num, i|
  result_str << "#{i} => #{num}\n"
end

puts result_str  #or add result_str to an email

--output:--
0 => a
1 => b
2 => c
Posted by 7stud -- (7stud)
on 2012-09-15 06:19
7stud -- wrote in post #1076100:
> arr = ['a', 'b', 'c']
> str = arr.each_with_index do |num, i|
>   puts "#{i} => #{num}"
> end
>

Whoops.  Chopped off a line there:

> p str


> --output:--
> 0 => a
> 1 => b
> 2 => c
> ["a", "b", "c"]
>
Posted by Edward QU (autogyro)
on 2012-09-15 07:46
Hi 7stud
cool, it works, thanks for your help!
cheer
Edward.
Please log in before posting. Registration is free and takes only a minute.
Existing account (Switch to SSL-encrypted connection)
NEW: Do you have a Google/GoogleMail or Yahoo account? No registration required!
Log in with Google account | Log in with Yahoo account
No account? Register here.