class Integer

Practical examples and pitfalls for Integer

Integer examples: split work and parse counts deliberately

Practical notes by Ruby-Doc.org

Calculate complete batches and a remainder together

A queue contains 53 jobs and each worker request accepts 10. You need both the number of complete requests and the remaining jobs. divmod returns those two answers together, which keeps their relationship visible in the code.

Example 1
jobs = 53
full, remainder = jobs.divmod(10)
requests = full + (remainder.zero? ? 0 : 1)
p [full, remainder, requests]
Expected output
[5, 3, 6]

If the queue is empty, the number of requests should be zero. If its size is exactly divisible by the batch size, do not send an extra empty request. These boundary cases are useful checks when adapting the example. Validate the batch size before division: zero is an error, and negative sizes do not describe the batching problem.

Reject a partially numeric setting

Configuration arrives as text more often than as an integer. If the entire value must be a decimal count, use Integer with base 10 rather than accepting a numeric prefix. Returning nil on failure lets the surrounding application decide how to report the invalid setting.

Example 2
p Integer("27", 10, exception: false)
p Integer("27jobs", 10, exception: false)
p "27jobs".to_i
Expected output
27
nil
27

Parsing establishes that a value represents an integer; it does not establish that the value is allowed. After conversion, check the application's minimum and maximum. A negative number may be valid Ruby and still make no sense as a retry count.

Choose the division result you actually need

Integer division does not retain a fractional part. Use fdiv when a floating-point ratio is appropriate, or quo when an exact rational result is useful. Converting a completed integer-division result to a float cannot restore a fraction already discarded.

For generated identifiers or flags, keep the representation decision at the boundary. A hexadecimal string can be useful for display while the stored value remains an integer. Avoid converting a number back and forth throughout a calculation merely to control how it will eventually be printed.

API reference: Integer API reference

Related: Float Β· Range

An Integer object represents an integer value.

You can create an Integer object explicitly with:

You can convert certain objects to Integers with:

An attempt to add a singleton method to an instance of this class causes an exception to be raised.

What’s Here

First, what’s elsewhere. Class Integer:

Here, class Integer provides methods for:

Querying

Comparing

Converting

Other