Class: PrimeTable::TabularView

Inherits:
Object
  • Object
show all
Defined in:
lib/prime_table.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(n: 10) ⇒ TabularView

initialize new object with default 10 prime numbers



40
41
42
43
# File 'lib/prime_table.rb', line 40

def initialize(n: 10)
  @table = []
  @prime_numbers = GetPrimes.fetch_primes(n)
end

Instance Attribute Details

#prime_numbersObject (readonly)

defining the state attributes



37
38
39
# File 'lib/prime_table.rb', line 37

def prime_numbers
  @prime_numbers
end

#tableObject (readonly)

defining the state attributes



37
38
39
# File 'lib/prime_table.rb', line 37

def table
  @table
end

Instance Method Details

#tableizeObject

shows the product output in STDOUT in tabular form



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/prime_table.rb', line 46

def tableize
  # format the header of the table
  # join all prime numbers with the calculated str_separator
  table_header = "%#{str_separator}s" % '#' # put '#' so to indicate the pointer to row and column conjunction
  @table <<  (table_header << @prime_numbers.collect {|s| "%#{str_separator+1}s" % s}.join(''))

  # get the multiplier value of the prime number with others
  @prime_numbers.map do |x|
    # push the value for the first column of the table
    str = "%#{str_separator}s" % x

    # extract the column values apart for subsequent columns
    @prime_numbers.collect{|w| str << "%#{str_separator+1}s" % (x * w) }

    # puts formatted string to table array
    @table << str
  end

  # displays the table on STDOUT
  @table
end