Show elements of array separated

K

Kless

Why when is showed an array into a variable , it is showed with all
characters followed?
 
R

Robert Klemme

Why when is showed an array into a variable , it is showed with all
characters followed?

irb(main):001:0> foo = %w{a b c}
=> ["a", "b", "c"]
irb(main):002:0> foo.to_s
=> "abc"
irb(main):003:0> foo.join ", "
=> "a, b, c"
irb(main):004:0>

Kind regards

robert
 
K

Kless

Thanks! I was too complicated:

irb(main):001:0> foo = ['a', 'b', 'c']
=> ["a", "b", "c"]
irb(main):002:0> s = ''
=> ""
irb(main):003:0> foo.each {|x| s += x.to_s + ', '}
=> ["a", "b", "c"]
irb(main):004:0> puts s[0..-3]
a, b, c
=> nil


Why when is showed an array  into a variable , it is showed with all
characters followed?
I'm supposed that is because at the first it converts the array into a
string. But is there any way of show the elements of array separated?

irb(main):001:0> foo = %w{a b c}
=> ["a", "b", "c"]
irb(main):002:0> foo.to_s
=> "abc"
irb(main):003:0> foo.join ", "
=> "a, b, c"
irb(main):004:0>

Kind regards

        robert
 
R

Robert Klemme

Thanks! I was too complicated:

irb(main):001:0> foo = ['a', 'b', 'c']
=> ["a", "b", "c"]
irb(main):002:0> s = ''
=> ""
irb(main):003:0> foo.each {|x| s += x.to_s + ', '}
=> ["a", "b", "c"]
irb(main):004:0> puts s[0..-3]
a, b, c
=> nil

If you want to do it manually, I'd rather do something like this:

irb(main):004:0> s = ""
=> ""
irb(main):005:0> foo.each_with_index {|x,i| s << ", " unless i == 0; s
<< i.to_s}
=> ["a", "b", "c"]
irb(main):006:0> s
=> "0, 1, 2"
irb(main):007:0>

Or even

irb(main):010:0> foo.inject {|a,b| "#{a}, #{b}"}
=> "a, b, c"
irb(main):011:0> ["a"].inject {|a,b| "#{a}, #{b}"}
=> "a"
irb(main):012:0> [].inject {|a,b| "#{a}, #{b}"}
=> nil
irb(main):013:0>

But note the empty Array case.

Kind regards

robert
 

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
474,201
Messages
2,571,049
Members
47,655
Latest member
eizareri

Latest Threads

Top