In my script (for Ruby >= 1.9) below I defined a Table class, which responsability is to generate 2 to 10 addition or multiplication table (chosen with a parameter). Then I call table method from a new Table instance in order to print result in a file.
This is the script :
#!/usr/bin/env ruby
class Table
HEADER_LINE = "="*25
add_operation = lambda { |op1, op2| op1 + op2 }
mul_operation = lambda { |op1, op2| op1 * op2 }
def table(req_operation = :mul)
operation, op_label = case req_operation
when :add
[add_operation, "+"]
when :mul
[mul_operation, "*"]
else
raise "Unknown operation #{req_operation} !"
end
(2..10).each do |op1|
yield HEADER_LINE
yield "Table de #{op1} (x#{op_label}y)"
yield HEADER_LINE
(1..10).each do |op2|
yield line = "#{op1} #{op_label} #{op2} = #{operation.call(op1, op2)}"
end
yield HEADER_LINE
yield
end
end
end
File.open("MyFile", "w") do |file|
Table.new.table do |line|
file.write "#{line}\n"
end
end
The parallel assignement on line 11 tries to set a lambda to operation and a string to op_label. Indeed, on line 26, I want to apply the lambda to op1 and op2 local variables.
But I get the following error :
./operation_table.rb:15:in `table': undefined local variable or method `mul_operation' for #<Table:0x00000000f1fc48> (NameError)
from ./operation_table.rb:38:in `block in <main>'
from ./operation_table.rb:37:in `open'
from ./operation_table.rb:37:in `<main>'
Is there a way to correct it while keeping the parallel assignement ?
Thanks in advance.
add_operationandmul_operationare local variables, declared outside the function, and cannot be accessed by the functiontable.You can declare it inside the table function, or store as class variables.