Forum: Ruby Re: Problem with MODULO function?

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.
60d5162f8b497bf35ee84b813a06bfbd?d=identicon&s=25 jan aerts (RI) (Guest)
on 2006-05-03 19:07
(Received via mailing list)
Hi Peter,

I think it has to do with the fact that numberofpages is a string
instead of an integer. In the irb:
> number_of_pages = 5
> number_of_pages % 2     => 1
> number_of_pages = '5'
> number_of_pages % 2     => 5

So the test (numberofpages % 2 != 0) will always return a false, unless
numberofpages was 0 in the first place.

Workaround: use ( numberofpages.to_i % 2 ) instead.

Jan.
A9b6a93b860020caf9d2d1d58c32478f?d=identicon&s=25 Ross Bamford (Guest)
on 2006-05-03 19:07
(Received via mailing list)
On Wed, 2006-05-03 at 21:21 +0900, jan aerts (RI) wrote:
> numberofpages was 0 in the first place.
>

Yes, String#% does something completely different:

# => "16768.181"
"%.3f" % 16768.181202317
# => "16768.181"
"%d" % 502
# => "502"
"An example of %s with %s" % ["formatting", "String#%"]
# => "An example of formatting with String#%"

ri 'String#%'
--------------------------------------------------------------- String#%
     str % arg   => new_str
------------------------------------------------------------------------
     Format---Uses _str_ as a format specification, and returns the
     result of applying it to _arg_. [...snipped...]


(P.s. seems to be a lot of top-posting going on these days :( )
This topic is locked and can not be replied to.