Ruby – Fixnum Documentation

Fixnum class Documentation

Ruby has many classes.

Now we are going to see about Fixnum class.

Fixnum contains these methods in default.

%

&

*

**

+

+@

-@

/

<

<<

<=

<=>

==

===

=~

>

>=

>>

[]

^

__id__

__send__

abs

between?

ceil

chr

class

clone

coerce

denominator

display

div

divmod

downto

dup

eql?

equal?

extend

floor

freeze

frozen?

gcd

gcdlcm

gem

hash

id

id2name

inspect

instance_eval

instance_of?

instance_variable_defined?

instance_variable_get

instance_variable_set

instance_variables

integer?

is_a?

kind_of?

lcm

method

methods

modulo

next

nil?

nonzero?

numerator

object_id

power!

prec

prec_f

prec_i

private_methods

protected_methods

public_methods

quo

rdiv

remainder

require

require_gem

respond_to?

round

rpower

send

singleton_method_added

singleton_methods

size

step

succ

taguri

taguri=

taint

tainted?

times

to_a

to_bn

to_f

to_i

to_int

to_r

to_s

to_sym

to_yaml

to_yaml_properties

to_yaml_style

truncate

type

untaint

upto

zero?

|

~

RDoc Documentation:

http://www.ruby-doc.org/core/

This page provides Documentation for these methods But each and every time need to select some class and files here.

So this article contains all the methods with the examples.

Method Example Description
% puts 5%3 => 2 Uses / to perform division, then converts the result to an integer. Numeric does not define the / operator; this is left to subclasses.
& puts 3&5 => 1 Binary AND

3 represents 0011

5 represents 0101 

Where the digits match exactly 1

0001 so output is -> 1

* puts 5*3 => 15 Multiplication
** puts 5**3 =>125 5*5*5 =125
+ puts 5+3 => 8 Addition
puts 5-3 => 2 Subtraction
-@ Negates fix (which might return a Bignum).
/ puts 5/3 => 1 5/3=1.66666 So output is 1
< puts 5<3 => false

puts 3<5 => true

Less than
<< puts 2 <<0 => 2

puts 2 <<1 => 4

puts 2 << 2 => 8

2 (0 time)

2*2 (1 time)

2*2*2 (2 times)

<= puts 3<=5 => true

puts 5<=3 => false

Less than or equal to
<=> puts 5 <=> 3 => 1

puts 5 <=> 5 => 0

puts 5 <=> 7 => -1

First number is big then return 1

Both are same then return 0

2nd number is big then return -1

== puts 5==3 => false

puts 5==5 => true

False – Different numbers.

True –both are Same numbers

=== puts 5===3 => false

puts 5===5 => true

False – Different numbers.

True –both are Same numbers

=~ Pattern Match—Overridden by descendents (notably Regexp and String) to provide meaningful pattern-match semantics.
> puts 5>3 => true

puts 3>5 => false

Greater than
>= puts 3>=5 => false

puts 5>=3 => true

Greater than or equal to
>> puts 4 >> 1 => 2

puts 4 >> 2 => 1

Ex.

4 >> 1

0100 – Shifts fix right(1 time) – 0010 = 2

4 >> 2

0100 – Shifts fix right (2 times) – 0001 = 1

Shifts fix right count positions (left if count is negative).
[] a = 0b11001100101010

30.downto(0) do |n| print a[n] end

produces:

0000000000000000011001100101010

Bit Reference—Returns the nth bit in the binary representation of fix, where fix[0] is the least significant bit.
^ puts 5^3 => 6 Bitwise EXCLUSIVE OR.
__id__ puts 5.__id__ => 11

puts 3.__id__ => 7

Returns an integer identifier for obj. The same number will be returned on all calls to id for a given object, and no two active objects will share an id. Object#object_id is a different concept from the :name notation, which returns the symbol id of name. Replaces the deprecated Object#id.
__send__ class Klass

def hello(*args)

“Hello ” + args.join(‘ ‘)

end

end

k = Klass.new

k.send :hello, “gentle”, “readers” #=> “Hello gentle readers”

Invokes the method identified by symbol, passing it any arguments specified. You can use __send__ if the name send clashes with an existing method in obj.
abs puts 5.abs => 5

puts -5.abs => 5

It gives the value without consider about plus or minus
between? puts 5.between?(3,8) => true

puts 5.between?(3,4) => false

5 is placed between 3 to 8

5 is not placed in between 3 to 4

ceil 1.ceil #=> 1

1.2.ceil #=> 2

(-1.2).ceil #=> -1

(-1.0).ceil #=> -1

Returns the smallest Integer greater than or equal to num. Class Numeric achieves this by converting itself to a Float then invoking Float#ceil.
chr puts 5.class => Fixnum

1.class #=> Fixnum

self.class #=> Object

Character of ascii values

Returns the class of obj, now preferred over Object#type, as an object‘s type in Ruby is only loosely tied to that object‘s class. This method must always be called with an explicit receiver, as class is also a reserved word in Ruby.

clone class Klass

attr_accessor :str

end

s1 = Klass.new #=> #

s1.str = “Hello” #=> “Hello”

s2 = s1.clone #=> #

s2.str[1,4] = “i” #=> “i”

s1.inspect #=> “#”

s2.inspect #=> “#”

This method may have class-specific behavior. If so, that behavior will be documented under the #initialize_copy method of the class.

Produces a shallow copy of obj—the instance variables of obj are copied, but not the objects they reference. Copies the frozen and tainted state of obj. See also the discussion under Object#dup.
coerce puts 5.coerce(3) => [3,5] If aNumeric is the same type as num, returns an array containing aNumeric and num. Otherwise, returns an array with both aNumeric and num represented as Float objects. This coercion mechanism is used by Ruby to handle mixed-type numeric operations: it is intended to find a compatible common type between the two operands of the operator.
denominator puts 2/5.denominator => 2

puts 5.denominator => 1

In an integer, the denominator is 1. Therefore, this method returns 1.
display def display(port=$>)

port.write self

end 

For example:

1.display

“cat”.display

[ 4, 5, 6 ].display

Puts

produces:

1cat456

Prints obj on the given port (default $>). Equivalent to:
div puts 12.div(2) => 6 Uses / to perform division, then converts the result to an integer. Numeric does not define the / operator; this is left to subclasses.
divmod puts 12.divmod(2) => [6,0]

puts 11.divmod(2) => [5,1]

puts 11.divmod(-3)=>[-4, -1]

Returns an array containing the quotient and modulus obtained by dividing num by aNumeric. If q, r = x.divmod(y), then

q = floor(float(x)/float(y))

x = q*y + r

The quotient is rounded toward -infinity, as shown in the following table:

downto 5.downto(1) { |n| print n, “.. ” }

print ” Liftoff!\n”

produces:

5.. 4.. 3.. 2.. 1.. Liftoff!

dup Produces a shallow copy of obj—the instance variables of obj are copied, but not the objects they reference. dup copies the tainted state of obj. See also the discussion under Object#clone. In general, clone and dup may have different semantics in descendent classes. While clone is used to duplicate an object, including its internal state, dup typically uses the class of the descendent object to create the new instance.

This method may have class-specific behavior. If so, that behavior will be documented under the #initialize_copy method of the class.

eql? 1 == 1.0 #=> true

1.eql?(1.0) #=> false

(1.0).eql?(1.0) #=> true

Returns true if num and numeric are the same type and have equal values.
equal? 1 == 1.0 #=> true

1.eql? 1.0 #=> false

Equality—At the Object level, == returns true only if obj and other are the same object. Typically, this method is overridden in descendent classes to provide class-specific meaning.

Unlike ==, the equal? method should never be overridden by subclasses: it is used to determine object identity (that is, a.equal?(b) iff a is the same object as b).

The eql? method returns true if obj and anObject have the same value. Used by Hash to test members for equality. For objects of class Object, eql? is synonymous with ==. Subclasses normally continue this tradition, but there are exceptions. Numeric types, for example, perform type conversion across ==, but not across eql?, so:

extend module Mod

def hello

“Hello from Mod.\n”

end

end 

class Klass

def hello

“Hello from Klass.\n”

end

end

k = Klass.new

k.hello #=> “Hello from Klass.\n”

k.extend(Mod) #=> #

k.hello #=> “Hello from Mod.\n”

Adds to obj the instance methods from each module given as a parameter.
floor 1.floor #=> 1

(-1).floor #=> -1

Returns the largest integer less than or equal to num. Numeric implements this by converting anInteger to a Float and invoking Float#floor.
freeze a = [ “a”, “b”, “c” ]

a.freeze

a << “z”

produces:

prog.rb:3:in `<<‘: can’t modify frozen array (TypeError)

from prog.rb:3

Prevents further modifications to obj. A TypeError will be raised if modification is attempted. There is no way to unfreeze a frozen object. See also Object#frozen?.
frozen? a = [ “a”, “b”, “c” ]

a.freeze #=> [“a”, “b”, “c”]

a.frozen? #=> true

Returns the freeze status of obj.
gcd 72.gcd 168 # -> 24

19.gcd 36 # -> 1

Returns the greatest common denominator of the two numbers (self and n).
gcdlcm .gcdlcm 9 # -> [3, 18] Returns the GCD and the LCM (see gcd and lcm) of the two arguments (self and other). This is more efficient than calculating them separately.
hash Generates a Fixnum hash value for this object. This function must have the property that a.eql?(b) implies a.hash == b.hash. The hash value is used by class Hash. Any hash value that exceeds the capacity of a Fixnum will be truncated before being used.
id2name symbol = :@inst_var #=> :@inst_var

id = symbol.to_i #=> 9818

id.id2name #=> “@inst_var”

Returns the name of the object whose symbol id is fix. If there is no symbol in the symbol table with this value, returns nil. id2name has nothing to do with the Object.id method. See also Fixnum#to_sym, String#intern, and class Symbol.
inspect [ 1, 2, 3..4, ‘five’ ].inspect #=> “[1, 2, 3..4, \”five\”]”

Time.new.inspect #=> “Wed Apr 09 08:54:39 CDT 2003”

Returns a string containing a human-readable representation of obj. If not overridden, uses the to_s method to generate the string.
instance_eval class Klass

def initialize

@secret = 99

end

end

k = Klass.new

k.instance_eval { @secret } #=> 99

Evaluates a string containing Ruby source code, or the given block, within the context of the receiver (obj). In order to set the context, the variable self is set to obj while the code is executing, giving the code access to obj‘s instance variables. In the version of instance_eval that takes a String, the optional second and third parameters supply a filename and starting line number that are used when reporting compilation errors.
instance_of? Returns true if obj is an instance of the given class. See also Object#kind_of?.
instance_variable_defined? class Fred

def initialize(p1, p2)

@a, @b = p1, p2

end

end

fred = Fred.new(‘cat’, 99)

fred.instance_variable_defined?(:@a) #=> true

fred.instance_variable_defined?(“@b”) #=> true

fred.instance_variable_defined?(“@c”) #=> false

Returns true if the given instance variable is defined in obj.
instance_variable_get class Fred

def initialize(p1, p2)

@a, @b = p1, p2

end

end

fred = Fred.new(‘cat’, 99)

fred.instance_variable_get(:@a) #=> “cat”

fred.instance_variable_get(“@b”) #=> 99

Returns the value of the given instance variable, or nil if the instance variable is not set. The @ part of the variable name should be included for regular instance variables. Throws a NameError exception if the supplied symbol is not valid as an instance variable name.
instance_variable_set class Fred

def initialize(p1, p2)

@a, @b = p1, p2

end

end

fred = Fred.new(‘cat’, 99)

fred.instance_variable_set(:@a, ‘dog’) #=> “dog”

fred.instance_variable_set(:@c, ‘cat’) #=> “cat”

fred.inspect #=> “#”

Sets the instance variable names by symbol to object, thereby frustrating the efforts of the class‘s author to attempt to provide proper encapsulation. The variable did not have to exist prior to this call.
instance_variables class Fred

attr_accessor :a1

def initialize

@iv = 3

end

end

Fred.new.instance_variables #=> [“@iv”]

Returns an array of instance variable names for the receiver. Note that simply defining an accessor does not create the corresponding instance variable.
integer? puts 5.integer? => true Always returns true.
is_a? module M; end

class A

include M

end

class B < A; end

class C < B; end

b = B.new

b.instance_of? A #=> false

b.instance_of? B #=> true

b.instance_of? C #=> false

b.instance_of? M #=> false

b.kind_of? A #=> true

b.kind_of? B #=> true

b.kind_of? C #=> false

b.kind_of? M #=> true

Returns true if class is the class of obj, or if class is one of the superclasses of obj or modules included in obj.
kind_of? module M; end

class A

include M

end

class B < A; end

class C < B; end

b = B.new

b.instance_of? A #=> false

b.instance_of? B #=> true

b.instance_of? C #=> false

b.instance_of? M #=> false

b.kind_of? A #=> true

b.kind_of? B #=> true

b.kind_of? C #=> false

b.kind_of? M #=> true

Returns true if class is the class of obj, or if class is one of the superclasses of obj or modules included in obj.
lcm 6.lcm 7 # -> 42

6.lcm 9 # -> 18

Returns the lowest common multiple (LCM) of the two arguments (self and other).
method class Demo

def initialize(n)

@iv = n

end

def hello()

“Hello, @iv = #{@iv}”

end

end 

k = Demo.new(99)

m = k.method(:hello)

m.call #=> “Hello, @iv = 99”

l = Demo.new(‘Fred’)

m = l.method(“hello”)

m.call #=> “Hello, @iv = Fred”

Looks up the named method as a receiver in obj, returning a Method object (or raising NameError). The Method object acts as a closure in obj‘s object instance, so instance variables and the value of self remain available.
methods class Klass

def kMethod()

end

end

k = Klass.new

k.methods[0..9] #=> [“kMethod”, “freeze”, “nil?”, “is_a?”,

“class”, “instance_variable_set”,

“methods”, “extend”, “__send__”, “instance_eval”]

k.methods.length #=> 42

Returns a list of the names of methods publicly accessible in obj. This will include all the methods accessible in obj‘s ancestors
modulo puts 5.modulo(3) => 2 Equivalent to num.divmod(aNumeric)[1].
next 1.next #=> 2

(-1).next #=> 0

Returns the Integer equal to int + 1.
nil? nil.nil? => true

.nil? => false

call_seq:

Only the object nil responds true to nil?.

nonzero? a = %w( z Bb bB bb BB a aA Aa AA A )

b = a.sort {|a,b| (a.downcase <=> b.downcase).nonzero? || a <=> b }

b #=> [“A”, “a”, “AA”, “Aa”, “aA”, “BB”, “Bb”, “bB”, “bb”, “z”]

Returns num if num is not zero, nil otherwise. This behavior is useful when chaining comparisons:
numerator puts 3.numerator => 3 In an integer, the value is the numerator of its rational equivalent. Therefore, this method returns self.
object_id Returns an integer identifier for obj. The same number will be returned on all calls to id for a given object, and no two active objects will share an id. Object#object_id is a different concept from the :name notation, which returns the symbol id of name. Replaces the deprecated Object#id.
power! puts 3.power!(2) => 9 Alias for #**
prec klass.induced_from(num)

and returns its value. So, if klass.induced_from doesn‘t return an instance of klass, it will be necessary to reimplement prec.

Converts self into an instance of klass. By default, prec invokes
prec_f Returns a Float converted from num. It is equivalent to prec(Float).
prec_i Returns an Integer converted from num. It is equivalent to prec(Integer).
private_methods Returns the list of private methods accessible to obj. If the all parameter is set to false, only those methods in the receiver will be listed.
protected_methods Returns the list of protected methods accessible to obj. If the all parameter is set to false, only those methods in the receiver will be listed.
public_methods Returns the list of public methods accessible to obj. If the all parameter is set to false, only those methods in the receiver will be listed.
quo 654321.quo(13731) #=> 47.6528293642124

654321.quo(13731.24) #=> 47.6519964693647

Returns the floating point result of dividing fix by numeric.
rdiv puts 5.rdiv(3) => rational(5,3) Alias for quo
remainder puts 5.remander(3) => 2 If num and numeric have different signs, returns mod-numeric; otherwise, returns mod. In both cases mod is the value num.modulo(numeric). The differences between remainder and modulo (%) are shown in the table under Numeric#divmod.
respond_to? Returns true> if obj responds to the given method. Private methods are included in the search only if the optional second parameter evaluates to true.
round puts 5.round => 5 Rounds num to the nearest integer. Numeric implements this by converting itself to a Float and invoking Float#round.
rpower puts 3.rpower(3) => 27 3*3*3
send class Klass

def hello(*args)

“Hello ” + args.join(‘ ‘)

end

end

k = Klass.new

k.send :hello, “gentle”, “readers” #=> “Hello gentle readers”

Invokes the method identified by symbol, passing it any arguments specified. You can use __send__ if the name send clashes with an existing method in obj.
singleton_method_added module Chatty

def Chatty.singleton_method_added(id)

puts “Adding #{id.id2name}”

end

def self.one() end

def two() end

def Chatty.three() end

end

produces:

Adding singleton_method_added

Adding one

Adding three

Invoked as a callback whenever a singleton method is added to the receiver.
singleton_methods module Other

def three() end

end 

class Single

def Single.four() end

end

a = Single.new

def a.one()

end

class << a

include Other

def two()

end

end

Single.singleton_methods #=> [“four”]

a.singleton_methods(false) #=> [“two”, “one”]

a.singleton_methods #=> [“two”, “one”, “three”]

Returns an array of the names of singleton methods for obj. If the optional all parameter is true, the list will include methods in modules included in obj.
size 1.size #=> 4

-1.size #=> 4

2147483647.size #=> 4

Returns the number of bytes in the machine representation of a Fixnum.
step 1.step(10, 2) { |i| print i, ” ” }

Math::E.step(Math::PI, 0.2) { |f| print f, ” ” }

produces:

1 3 5 7 9

2.71828182845905 2.91828182845905 3.11828182845905

Invokes block with the sequence of numbers starting at num, incremented by step on each call. The loop finishes when the value to be passed to the block is greater than limit (if step is positive) or less than limit (if step is negative). If all the arguments are integers, the loop operates using an integer counter. If any of the arguments are floating point numbers, all are converted to floats, and the loop is executed floor(n + n*epsilon)+ 1 times, where n = (limit – num)/step. Otherwise, the loop starts at num, uses either the < or > operator to compare the counter against limit, and increments itself using the + operator.
succ 1.next #=> 2

(-1).next #=> 0

Returns the Integer equal to int + 1.
taint Marks obj as tainted—if the $SAFE level is set appropriately, many method calls which might alter the running programs environment will refuse to accept tainted strings.
tainted? Returns true if the object is tainted.
times 5.times do |i|

print i, ” ”

end

produces:

0 1 2 3 4

Iterates block int times, passing in values from zero to int – 1.
to_a self.to_a #=> -:1: warning: default `to_a’ will be obsolete

“hello”.to_a #=> [“hello”]

Time.new.to_a #=> [39, 54, 8, 9, 4, 2003, 3, 99, true, “CDT”]

Returns an array representation of obj. For objects of class Object and others that don‘t explicitly override the method, the return value is an array containing self. However, this latter behavior will soon be obsolete.
to_f puts 5.to_f => 5.0 Converts fix to a Float.
to_i puts 5.to_i => 5 As int is already an Integer, all these methods simply return the receiver.
to_int puts 5.to_i nt => 5 Invokes the child class‘s to_i method to convert num to an integer.
to_r puts 5.to_r => Rational(5,1) Returns a Rational representation of this integer.
to_s 12345.to_s #=> “12345”

12345.to_s(2) #=> “11000000111001”

12345.to_s(8) #=> “30071”

12345.to_s(10) #=> “12345”

12345.to_s(16) #=> “3039”

12345.to_s(36) #=> “9ix”

Returns a string containing the representation of fix radix base (between 2 and 36).
to_sym fred = :fred.to_i

fred.id2name #=> “fred”

fred.to_sym #=> :fred

Returns the symbol whose integer value is fix. See also Fixnum#id2name.
truncate Returns num truncated to an integer. Numeric implements this by converting its value to a float and invoking Float#truncate.
type Deprecated synonym for Object#class.
untaint Removes the taint from obj.
upto 5.upto(10) { |i| print i, ” ” }

produces:

5 6 7 8 9 10

Iterates block, passing in integer values from int up to and including limit.
zero? puts 5.zero? => false Returns true if fix is zero.
| puts 5|3 => 7 Bitwise OR.
~ puts ~5 => -6 One‘s complement: returns a number where each bit is flipped.

Comments are always welcome

Advertisements

5 thoughts on “Ruby – Fixnum Documentation

  1. RaiulBaztepo says:

    Hello!
    Very Interesting post! Thank you for such interesting resource!
    PS: Sorry for my bad english, I’v just started to learn this language 😉
    See you!
    Your, Raiul Baztepo

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s