Just starting to learn Ruby, I’d like to ask if somebody would be so
kind as to help me ‘translate’ this Perl proof of concept code:
package cApp;
# POC application class that can run named Fncs via 'pointer to
function’
my %Fncs = ( 'frsFnc' => [ 'just tell "frsFnc"', \&frsFnc ]
, 'secFnc' => [ 'just tell "secFnc"', \&secFnc ]
);
sub new
{ my $class = shift;
my $self = { name => shift
, Fncs => \%Fncs
};
bless( $self, $class );
}
sub run
{ my $self = shift;
my $sFnc = shift;
if( exists( $self->{ Fncs }->{ $sFnc } ) )
{ &{$self->{ Fncs }->{ $sFnc }->[ 1 ]}( $self )
}
else
{ print "no '$sFnc' in: ", join( ' ', keys( %{$self->{ Fncs }}
) ), “\n”;
}
}
sub frsFnc
{ my $self = shift;
print $self->{ name }, '::frsFnc', "\n";
}
sub secFnc
{ my $self = shift;
print $self->{ name }, '::secFnc', "\n";
}
package main;
# main: create instance of cApp, get Fnc name, run named Fnc
my $oApp = cApp->new( 'trivial' );
my $sFnc = $ARGV[ 0 ] || 'frsFnc';
$oApp->run( $sFnc );
to Ruby. That’s what I have now:
class CAPP
@name = 'anonym'
@Fncs = nil
def to_s
'POC application class that can run named Fncs via "pointer to
function"’
end
def initialize( name )
@name = name
@Fncs = { 'frsFnc' => [ 'just tell "frsFnc"', nil ] ,
'secFnc' => [ 'just tell "secFnc"', nil ]
}
end
def run( sFnc )
puts @name + '::run( "' + sFnc + '" )'
if @Fncs.has_key?( sFnc )
puts "can't call fnc by name yet"
else
puts 'no ' + sFnc + ' in: ' + @Fncs.keys.join( ' ' )
end
end
def frsFnc
puts @name + '::frsFnc'
end
def secFnc
puts @name + '::secFnc'
end
end # class CAPP
# main: create instance of cApp, get Fnc name, run named Fnc
oApp = CAPP.new( 'trivial' )
puts oApp.to_s
puts "That's easy:"
oApp.frsFnc()
oApp.secFnc()
sFnc = ARGV[ 0 ] || 'frsFnc'
puts "Now call " + sFnc + ', please:'
oApp.run( sFnc )
Is it possible to replace the “nil” in @Fncs and the
puts “can’t call fnc by name yet”
in run() with suitable Ruby expressions/statements?
I looked at lamba, but I don’t want to define the functions using
strings.
Thanks