displaying an array

7

7stud 7stud

In irb, an array displays like this:

irb(main):001:0> a = %w(bird dog cat)
=> ["bird", "dog", "cat"]
irb(main):002:0>

Is there a command to get the same format when I display an array with a
program?

r1test.rb:
----------
a1 = %w(cat dog bird)
puts a1

$ ruby r1test.rb
cat
dog
bird


Also, this code:

----------
a1 = %w(cat dog bird)
puts a1

puts

a2 = %w{john joe jim}
puts a2

--output:--
cat
dog
bird
john
joe
jim
-----------------

seems to suggest that braces and parentheses are equivalent. Is that
the case?

Thanks
 
S

Sebastian Hungerecker

7stud said:
In irb, an array displays like this:

irb(main):001:0> a = %w(bird dog cat)
=> ["bird", "dog", "cat"]
irb(main):002:0>

Is there a command to get the same format when I display an array with a
program?

p (which is equivalent to puts foo.inspect)

Also, this code:

a1 = %w(cat dog bird)
puts a1

a2 = %w{john joe jim}
puts a2
[...]
seems to suggest that braces and parentheses are equivalent. Is that
the case?

You can use any non-alphanumeric character with %w (or %r or whatever). It
won't make a difference. Examples:
%w<la lu li>
%w_li la lo_
%w#chunky bacon#
%w)foo bar) # This one's strange, I know.
etc.

HTH,
Sebastian
 
G

Gavin Kistner

7stud said:
In irb, an array displays like this:

irb(main):001:0> a = %w(bird dog cat)
=> ["bird", "dog", "cat"]
irb(main):002:0>

Is there a command to get the same format when I display an array with a
program?

C:\>type p.rb
a = %w(cat dog bird)
p a

C:\>ruby p.rb
["cat", "dog", "bird"]
 
7

7stud 7stud

Sebastian said:
p (which is equivalent to puts foo.inspect)


You can use any non-alphanumeric character with %w (or %r or whatever).
It won't make a difference.

Thanks Sebastian. Thanks Gavin.
 

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

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,011
Latest member
AjaUqq1950

Latest Threads

Top