I'm new to ruby and trying to duplicate this perl, that calls anonymous subroutines, in ruby:
#!/usr/bin/perl
use strict;
use warnings;
use feature 'say';
# Make a reference to a subroutine
my $codes = {
one => sub {
say "This is code block one";
say "And this is code block one's line two"
},
};
for my $next_code ( keys %{ $codes } ) {
# Execute anonymous subroutine
&{ $codes->{ $next_code } };
}
I tried this:
#!/usr/bin/ruby -w
codes = {
one: puts "This is code block one"
puts "And this is code block one's line two",
}
codes.each do |next_code|
next_code
end
But, I get syntax errors. Is this possible, or is there another preferred ruby way?
UPDATE: Yes, this is like a dispatch table. I store code in a hash and run that code later.
&{ $codes->{ $next_code } }is best written$codes->{ $next_code }->()