$><<@people.inject(){|a,p|a<<p if a.length<5;a}*"\n"
···
On Saturday 18 August 2007 04:09:16 am Konrad Meyer wrote:
On Saturday 18 August 2007 02:55:17 am Bob Sanders wrote:
> 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?
One idea comes to mind:
@people.inject(){|a,p|a<<p if a.length<5;a}.each{|p|puts p}
if you need only to puts on screen you can use the solution of stefano, but
it's usefull??
Maybe you need to search, operate on the range item, i think.
Bye
···
2007/8/18, Eric <eric-news@xs4all.nl>:
Op za 18 aug 12:03:56 2007 CEST schreef Andrea Forlin in > de nieuwsgroep 'comp.lang.ruby':
>
> @people[0..4].each { |item| puts item }
>
> -----Messaggio originale-----
> Da: list-bounce@example.com [mailto:list-bounce@example.com] Per conto
di
> Bob Sanders
> Inviato: sabato 18 agosto 2007 11.55
> A: ruby-talk ML
> Oggetto: How do you print the first 5 records in an array?
>
> 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?
I'd do it like this:
> puts @people[0..4]
Jim
Jen
Jess
Jay
Jack
=> nil
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[i]}
0.upto(4) {|i| puts @people[i]}
# might be less efficient but
# very readable
puts @people[0,5]
puts @people[0...5]
puts @people[0..4]
Note: it's not too unlikely that those variants with the sub arrays are actually faster, because that is all done in C code.
Cheers
robert
···
On 18.08.2007 13:14, Konrad Meyer wrote:
On Saturday 18 August 2007 04:09:16 am Konrad Meyer wrote:
On Saturday 18 August 2007 02:55:17 am Bob Sanders wrote:
puts(*@people.first(5))
Ruby, so surprisingly unsurprising
I don't think you need the * there.
David
Darn, and just when you say it is unsurprising you hit a surprising
thing.
Right, I keep forgetting that puts treats Arrays differently than every
other object.
Thanks for pointing out