0

H! I have the following (sniped script). I have a class with multiple definitions, I want to iterate through those definitions until some definition returns true so I thought to put them into an array and iterate, my problem is that when I want to access that definition through its class when I substitute the name of the definition so I can use it in a while loop I can't do that because it returns me errors. Any idea how to do that?

#...
class FetchHash
  def get_img_eight(something)
    #...
  end

  def get_img_seven(someting)
    #...
  end

  def get_img_six(something)
    #...
  end

  def get_img_five(something)
    #...
  end
end

get_cmds = [ "get_img_eight", "get_img_seven", "get_img_six", "get_img_five" ]
fetchme = FetchHash.new

for get_cmd in (get_cmds)
  while my_ret_hash.nil? do
    mynotworkingcmd = "fetchme.#{get_cmd}"
    my_ret_hash = mynotworkingcmd(something)
    break if my_ret_hash.nil?
  end
end

#...

The error:

./test:85:in `block in <main>': undefined method `mynotworkingcmd' for main:Object (NoMethodError)
        from ./test.rb:82:in `each'
        from ./test:82:in `<main>'

Line 85 in this sniped corresponds to my_ret_hash = mynotworkingcmd(something)

bsteo
  • 1,738
  • 6
  • 34
  • 60

1 Answers1

1

One way to do that is by using public_send like so:

get_cmds = [ "get_img_eight", "get_img_seven", "get_img_six", "get_img_five" ]
fetchme = FetchHash.new

for get_cmd in (get_cmds)
  while my_ret_hash.nil? do
    my_ret_hash = fetchme.public_send(cmd.to_sym, something)
    break if my_ret_hash.nil?
  end
end
Surya
  • 15,703
  • 3
  • 51
  • 74