Getting rid of a while loop


#1

I get a feeling there should be another way to make this happen without
using a while loop, if anyone has any ideas that’d be great.

while question=file.gets
  answer=file.gets
  @question_array[counter]=Questions.new(question,answer, false)
  counter+=1
end

#2

On Jun 7, 2006, at 7:53 AM, Tait P. wrote:

I get a feeling there should be another way to make this happen
without
using a while loop, if anyone has any ideas that’d be great.

while question=file.gets
  answer=file.gets
  @question_array[counter]=Questions.new(question,answer, false)
  counter+=1
end

One way would be:

require “enumerator”

file.each_slice(2) do |question, answer|
@question_array << Questions.new(question, answer, false)
end

Hope that helps.

James Edward G. II


#3

2006/6/7, James Edward G. II removed_email_address@domain.invalid:

end

One way would be:

require “enumerator”

file.each_slice(2) do |question, answer|
@question_array << Questions.new(question, answer, false)
end

Thanks for leaving the inject version for me. :slight_smile:

@question_array = file.to_enum(:each_slice, 2).inject([]) do |qa,(quest,
answ)|
qa << Questions.new(quest, answ, false)
end

:-))

robert


#4

while (questiom,answer = file.gets,file.gets) ?

Farrel


#5

without

@question_array = file.to_enum(:each_slice, 2).inject([]) do
|qa,(quest, answ)|
qa << Questions.new(quest, answ, false)
end

:-))

robert

hehe, nice, with 1.8.4

@question_array = file.enum_slice(2).map{|q, a| Questions.new(q, a,
false)}

should be possible, isn’t it?

cheers

Simon


#6

this is really strange!

d:\workspace>ruby -v
ruby 1.8.4 (2005-12-24) [i386-mswin32]

irb(main):009:0> [1,2,3].methods.grep(/slice/)
=> [“slice”, “slice!”]

the methods ‘each_slice’ and ‘enum_slice’ do not exist…

is this a bug of the windows build?


#7

Chris schrieb:

you forgot to
require ‘enumerator’

cheers

aaahhhh :-))

thanks so much!!


#8

you forgot to
require ‘enumerator’

cheers