How do you print the first 5 records in an array?

B

Bertram Scharpf

Hi,

Am Samstag, 18. Aug 2007, 18:55:17 +0900 schrieb Bob Sanders:
How would I then print out the first 5 records of that array?

Depending on what you want to do further maybe this is worth
a consideration:

5.times { puts @people.shift }

Bertram
 
F

Florian Frank

Robert said:
Although I'm always fond of solutions using #inject in this case I'm
sorry to say that but this is not only inefficient but totally
obfuscated. If you feel you have to iterate then you can immediately
print members. These are my preferred solutions

# fast and readable
5.times {|i| puts @people}
0.upto(4) {|i| puts @people}

# might be less efficient but
# very readable
puts @people[0,5]
puts @people[0...5]
puts @people[0..4]

Then let's at least use inject to create nice CPS-style solution:

puts_first_five = (0...5).inject(lambda {}) { |f, i| lambda { |a| f[a];
puts a } }
puts_first_five[@people]
 
F

Florian Aßmann

Bertram said:
Hi,

Am Samstag, 18. Aug 2007, 18:55:17 +0900 schrieb Bob Sanders:

Depending on what you want to do further maybe this is worth
a consideration:

5.times { puts @people.shift }

Bertram

No need to iterate here, just
puts @people.slice!(0,5)


but personally I like
puts @people.first(5)
the most...


Regards
Florian
 
A

Alin Popa

Bob said:
Let's say I have an array defined as:

@people = ["Jim", "Jen", "Jess", "Jay", "Jack", "John", "Jeff", "Jed",
"Jill"]

How would I then print out the first 5 records of that array? (i.e. from
Jim to Jack)

Any ideas?

5.times{|t| puts @people[t]}
 
E

Eric

Op zo 19 aug 01:17:56 2007 CEST schreef Florian Aßmann in
de nieuwsgroep 'comp.lang.ruby':
but personally I like
puts @people.first(5)
the most...

@array.first(5) reads exactly like 'the first 5 things' from the array...

Not without reason, i guess.

So, why do it another way?
 

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,792
Messages
2,569,639
Members
45,353
Latest member
RogerDoger

Latest Threads

Top