Forum: Ruby using count += 1, code won't change value in output

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Cf63da956b6ba955687a2f2f262928cb?d=identicon&s=25 Mmcolli00 Mom (mmcolli00)
on 2008-12-17 16:30
This is supposed to count every line in a file that contails the string
'0004343' however, when I use the puts it will only output 1 and 0. My
file contains 8 instances of '0004343' so I know that this isn't right.
I was thinking that it never changes the value to what happens to it in
the while loop. I know this is probably really simple. I just can't get
it. Please help me? MC

@count = 1
 @total = 0
  while line = f1.gets
    if f1.gets =~ /0004343/ then
     @total = @count+= 1
    end
 end
puts @count
puts @total
B32a1911d783e0a95e0b062fd5d0b64b?d=identicon&s=25 Jan Friedrich (janfri)
on 2008-12-17 16:35
Mmcolli00 Mom wrote:
> This is supposed to count every line in a file that contails the string
> '0004343' however, when I use the puts it will only output 1 and 0. My
> file contains 8 instances of '0004343' so I know that this isn't right.
> I was thinking that it never changes the value to what happens to it in
> the while loop. I know this is probably really simple. I just can't get
> it. Please help me? MC
>
> @count = 1
>  @total = 0
>   while line = f1.gets
>     if f1.gets =~ /0004343/ then
>      @total = @count+= 1
>     end
>  end
> puts @count
> puts @total

Change line 4 to:
     if line =~ /0004343/ then

You read twice from the file.

Regards,
Jan
Cf63da956b6ba955687a2f2f262928cb?d=identicon&s=25 Mmcolli00 Mom (mmcolli00)
on 2008-12-17 16:55
thanks
134ea397777886d6f0aa992672a50eaa?d=identicon&s=25 Mark Thomas (Guest)
on 2008-12-17 20:12
(Received via mailing list)
On Dec 17, 10:23 am, Mmcolli00 Mom <mmc_coll...@yahoo.com> wrote:
> This is supposed to count every line in a file that contails the string
> '0004343'

f1.grep(/0004343/).size

-- Mark.
This topic is locked and can not be replied to.