How do I call a method that is a hash value?
that code doesn't work. it executes a
at the time it is added to the hash, not when it is retrieved from the hash (try it in irb).
It doesn't work in the class because there is no a
method defined on the class (you eventually define a method a
on the instance.
Try actually using lambdas like
{0 => lambda { puts "hello world" }}
instead
How to call function on object coming from Hash-table value in c#
You should create an interface (or base class), then have a Dictionary storing objects implementing that interface, like in this example:
using System.Collections.Generic;
interface IEvaluation {
void StartEvaluation();
}
class LocationEvaluation : IEvaluation {
public void StartEvaluation() {
// do something...
}
}
class AssetEvaluation : IEvaluation {
public void StartEvaluation() {
// do something...
}
}
class Program {
static void Main(string[] args) {
// fill dictionary with IEvaluation objects
Dictionary<string, IEvaluation> evaluations = new Dictionary<string, IEvaluation>();
evaluations["LocationEvaluation"] = new LocationEvaluation();
evaluations["AssetEvaluation"] = new AssetEvaluation();
// get an object from the dictionary and call the function on it
IEvaluation evaluation = evaluations["AssetEvaluation"];
evaluation.StartEvaluation();
}
}
Storing a function in the value for a key within a hash
You can use the send keyword
send h[step]
since you writing the method name directly in value part of the hash, the call is being made, but If you store the method names as a string and then if you call by send method as shown below, it would work.
def hi
puts 'hi'
end
def hello
puts 'hello'
end
h = {
1 => 'hi',
2 => 'hello',
}
send h[1]
Store functions in hash
Not exactly like this, no. You need to get a hold of the Method
proxy object for the method and store that in the Hash
:
hash = { 'v' => method(:show_version) }
And you need to call
the Method
object:
hash['v'].()
Method
duck-types Proc
, so you could even store simple Proc
s alongside Method
s in the Hash
and there would be no need to distinguish between them, because both of them are called the same way:
hash['h'] = -> { puts 'Hello' }
hash['h'].()
# Hello
How do I use hash keys as methods on a class?
def method_missing(name, *args, &blk)
if args.empty? && blk.nil? && @attributes.has_key?(name)
@attributes[name]
else
super
end
end
Explanation: If you call a method, which does not exist, method_missing is invoked with the name of the method as the first parameter, followed by the arguments given to the method and the block if one was given.
In the above we say that if a method, which was not defined, is called without arguments and without a block and the hash has an entry with the method name as key, it will return the value of that entry. Otherwise it will just proceed as usual.
Calling a Javascript function from a hash value with namespaces
This should work:
$(function() {
var hash = window.location.hash.substring(1);
window.help[hash]();
});
In JavaScript dot notation and square brackets are interchangeable, as long as the key is a valid JavaScript identifier. (Otherwise, you have to use square brackets.)
So you could also do this (although dot notation is more readable):
$(function() {
var hash = window.location.hash.substring(1);
window["help"][hash]();
});
How to call a function from hash in perl
I decided to enhance your code:
#!/usr/bin/perl
#App.pm
use strict; use warnings;
package App;
use OtherModule;
use Other2Module;
my $hash = {
login => \&OtherModule::login,
logout => \&Other2Module::logout,
};
sub hashF
{
my($module, @params) = @_;
return $hash->{$module}->(@params);
}
We cannot assign bare names, but we can pass around code references. The &
Sigil denotes the "code" type or a subroutine, and \
gives us a reference to it. (Not getting a reference would execute the code; not something we want. Never execute &subroutine
unprovoked.)
BTW: Hashes can only hold scalar values, and (code) references are a kind of scalar.
When we want to call our sub from the hash, we have to use the dereference operator ->
.$hash->{$module}
returns a code reference as value; ->(@arglist)
executes it with the given arguments.
Another BTW: Don't write App::hashF
unless you are working inside an external module. You can declare your current namespace by writing package App
or whatever name you like (should correspond with path/name of .pm file).
Related Topics
Rails 3 Caching: Expire Action for Named Route
Native Threads in Ruby 1.9.1, Whats in It for Me
Ruby -- Capitalize First Letter of Every Sentence in a Paragraph
Cron Is Running in Home Directory Instead of File Directory
How to Create an Operator for Deep Copy/Cloning of Objects in Ruby
Do I Need to Indent My Code in Ruby
How to Enable Colors with Rspec When Using Jruby or Bundle Exec
Why #!/Usr/Bin/Env Ruby Doesn't Work in Crontab
Losing an Attribute When Saving Through an Association W/ Scope (Rails 4.0.0)
Callback for Active Storage File Upload
How to Set Up the Recipient Id in Public Activity
Rails 5 - Using Polymorphic Associations - Rendering the Views
Routing Error No Route Matches [Get] "/Static_Pages/Home", Tutorial
How to Call a Method That Is a Hash Value
Ruby Optionparser Empty Switch "-" Behavior
How to Render a Layout Directly from Routes.Rb, Without a Controller