Question

I am having a small problem with a method in Ruby. "information" is a hash that I want to iterate through, format the value if necessary and save a new hash with the formatted/changed pairs. The following:

formatted_information = {}     

information.each do |key, value|
  formatted_information[:"#{key}"] = self.send("format_#{key}(#{value})")
end

is supposed to call another method in the same document that handles the formatting (so if the key "name" was found it should run "format_name" with the corresponding value). Although the method exists I get the following error:

NoMethodError: undefined method `format_name("Some Name")'

What mistake am I making here?

Possible input: information = {:name => "A Name"}

Expected output: formatted_information = {:name => "B Name"}

Was it helpful?

Solution

send accepts the method name as the first argument, and the arguments to that method as the second argument. You should use

send("format_#{key}", value)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top