Reputation: 842
I have read about sending method names as parameters in ruby, however in my case I want to allow the user to select a Digest format and use the answer to set the digest type:
def hash_digest(file, argument)
format = Digest::argument.new #using the argument here
...
end
hash_digest(filename, :MD5)
I have tried:
def hash_digest(file, argument)
format = Digest::send(argument).new
...
end
hash_digest(filename, :MD5)
But I get a no method `md5' error, despite MD5 being a valid algorithm in the Digest method. The exact error is:
send': undefined method MD5' for Digest:Module (NoMethodError) –
Is this possible in ruby?
Upvotes: 0
Views: 166
Reputation: 4730
I believe this works:
require 'digest'
def hash_digest(file, digest_algorithm)
format = Digest.const_get(digest_algorithm).new
end
hash_digest('test', 'SHA256')
Also since the number of options is fairly small you could always just use a case
statement:
require 'digest'
def hash_digest(file, digest_algorithm)
format = case digest_algorithm
when 'HMAC' then Digest::HMAC.new
when 'MD5' then Digest::MD5.new
when 'RMD160' then Digest::RMD160.new
when 'SHA1' then Digest::SHA1.new
when 'SHA256' then Digest::SHA256.new
when 'SHA384' then Digest::SHA384.new
when 'SHA512' then Digest::SHA512.new
end
end
hash_digest('test', 'SHA256')
Upvotes: 1