Using a string as a function name

I need to create a generic function that is used to call many other functions depending on access to them. For Ex:

def func1 @access = ['public','private','protected'] for acc in @access @temp = "get_"+acc[1]+"_data" end end def get_public_data end def get_private_data end def get_protected_data end 

but @temp takes it as a string and assigns it. Please help with this as soon as possible.

thanks

+1
source share
3 answers

In Ruby, methods are actually messages. Thus, you can send the message name using the yup, send method:

 s = 'xyz' i = s.send 'length' # i = 3 
+3
source
 @temp = send "get_#{acc[1]}_data" 

Use #{acc[1]} instead of "+"

+2
source

I don’t know which language you use, but some languages, i.e. Perl, have eval () that do what you are trying.

If you use Perl or Python, you can try something like

@temp = eval ("get _" + acc 1 + "_ data")

0
source

Source: https://habr.com/ru/post/887513/


All Articles