I have been given the 3 functions below. Can anybody please help me to understand these? I am trying to port an application to C++ using Qt, but I don’t understand these functions. So please help me!
Thanks in advance.
function 1:
def read_key
puts "read pemkey: \"#{@pkey}\"" if @verbose
File.open(@pkey, 'rb') do |io|
@key = OpenSSL::PKey::RSA.new(io)
end
end
function 2:
def generate_key
puts "generate pemkey to \"#{@pkey_o}\"" if @verbose
@key = OpenSSL::PKey::RSA.generate(KEY_SIZE)
# save key
File.open(@pkey_o, 'wb') do |file|
file << @key.export()
end
end
function 3:
def sign_zip
puts "sign zip" if @verbose
plain = nil
File.open(@zip, 'rb') do |file|
plain = file.read
end
@sig = @key.sign(OpenSSL::Digest::SHA1.new, plain)
end
There are probably two things about the above code that are confusing you, which if clarified, will help understand it.
First, @verbose and @key are instance variables, what a C++ programmer might call “member variables.” The “if @verbose” following the puts statement literally means only do the puts if @verbose is true. @verbose never needs to be declared a bool–you just start using it. If it’s never initialized, it’s “nil” which evaluates to false.
Second, the do/end parts are code blocks. Many Ruby methods take a code block and execute it with a variable declared in those pipe characters. An example would be “array.each do |s| puts s; end” which might look like “for(int i = 0; i < array.size(); ++i) { s = array[i]; puts(s); }” in C++. For File.open, |io| is the file instance opened, and “read” is one of its methods.