Class: Fixnum

Inherits:
Object
  • Object
show all
Defined in:
lib/bitlab.rb,
lib/rubylabs.rb

Overview

Fixnum

When the RubyLabs module is loaded it defines a new method named ord to the Fixnum class. In Ruby 1.8, using the [] operator to access items in a String object returns the ASCII value of a character. The ord method defined here (and used by hash functions defined in hashlab.rb) maps the ASCII value of a letter to a number between 0 and 25.

The BitLab module also extends Fixnum by defining a method named code that returns a Code object containing the binary or hexadecimal representation of an integer. #– NOTE: ord is built in to Ruby 1.9, so this method will have to be renamed or reimplemented when RubyLabs is ported to 1.9.

Instance Method Summary collapse

Instance Method Details

#code(*args) ⇒ Object

Create a Code object showing the binary or hexadecimal representation of this number. The two arguments, both optional, define the type of representation and the number of digits:

x.code            make a binary code for x, using as many bits as necessary
x.code(n)         make a binary code for x, using n bits
x.code(:hex)      make a hex code for x, using as many digits as necessary
x.code(:hex,n)    make a hex code for x, using n digits (i.e. 4*n bits)

Example:

>> x = 26
=> 26
>> x.code
=> 11010
>> x.code(8)
=> 00011010
>> x.code(:hex)
=> 1A
>> x.code(:hex, 3)
=> 01A


1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
# File 'lib/bitlab.rb', line 1021

def code(*args)
  if args.first == :hex
    base = args.shift
  else
    base = :binary
  end
  if args.first.kind_of? Integer
    digits = args.shift
  elsif args.empty?
    b = (self == 0) ? 1 : log2(self+1).ceil
    digits = (base == :hex) ? (b/4.0).ceil : b
  else
    raise "code: can't understand #{args}"
  end
  if base == :hex
    return HexCode.new(self, 4*digits)
  else
    return Code.new(self, digits)
  end
  # bits = (base == :hex) ? digits * 4 : digits
  # return Code.new(self, bits, base)
end

#ordObject

If a number is the ASCII code for a letter from the Roman alphabet (upper or lower case, in the range ‘A’ to ‘Z’) map it to a number between 0 and 25, otherwise just return the value of the number.

Example:

>> "Ducks!".each_byte { |x| puts x.ord }
3
20
2
10
18
33


1544
1545
1546
1547
1548
1549
1550
1551
1552
# File 'lib/rubylabs.rb', line 1544

def ord
  if self >= ?a && self <= ?z
    self - ?a
  elsif self >= ?A && self <= ?Z
    self - ?A
  else
    self
  end
end