Вызов метода из строки с именем метода в Ruby

Более простой способ - просто сгенерировать SVG в строку, создать HTML-элемент оболочки и вставить строку svg в элемент HTML с помощью $("#wrapperElement").html(svgString). Это прекрасно работает в Chrome и Firefox.

146
задан mu is too short 22 February 2019 в 18:02
поделиться

3 ответа

To call functions directly on an object

a = [2, 2, 3]
a.send("length")
# or
a.public_send("length")

which returns 3 as expected

or for a module function

FileUtils.send('pwd')
# or
FileUtils.public_send(:pwd)

and a locally defined method

def load()
    puts "load() function was executed."
end

send('load')
# or
public_send('load')

Documentation:

222
ответ дан 23 November 2019 в 22:15
поделиться

Personally I would setup a hash to function references and then use the string as an index to the hash. You then call the function reference with it's parameters. This has the advantage of not allowing the wrong string to call something you don't want to call. The other way is to basically eval the string. Do not do this.

PS don't be lazy and actually type out your whole question, instead of linking to something.

3
ответ дан 23 November 2019 в 22:15
поделиться

Use this:

> a = "my_string"
> meth = a.method("size")
> meth.call() # call the size method
=> 9

Simple, right?

As for the global, I think the Ruby way would be to search it using the methods method.

33
ответ дан 23 November 2019 в 22:15
поделиться