Skip to content

Is it possible to modify an object that is passed as an argument and get it back on Ruby? #16

@cirosantilli

Description

@cirosantilli

Doesn't seem so:

require 'schmooze'
class BabelSchmoozer < Schmooze::Base
  method :version, 'function(mydict) { mydict["b"] = 2}'
end
babel = BabelSchmoozer.new(__dir__)
mydict = { 'a': 1 }
babel.version(mydict)
puts mydict

outputs:

{:a=>1}

But I found a reasonable workaround, which is to pass the value back on the return, and use an array of return values if I need more than one return object:

require 'schmooze'
class BabelSchmoozer < Schmooze::Base
  method :version, 'function(mydict) { mydict["b"] = 2; return mydict}'
end
babel = BabelSchmoozer.new(__dir__)
mydict = { 'a': 1 }
mydict = babel.version(mydict)
puts mydict

outputs:

{"a"=>1, "b"=>2}

and if the goal is to preserve a state parameter across calls, you can use the global object itself!

require 'schmooze'
class BabelSchmoozer < Schmooze::Base
  dependencies babel: 'babel-core'

  method :init, 'function() { babel.cirosantilli_mydict = []; }'
  method :version, 'function(val) { babel.cirosantilli_mydict.push(val); return babel.cirosantilli_mydict; }'
end
babel = BabelSchmoozer.new(__dir__)
babel.init
puts babel.version(0)
puts babel.version(1)

Tested on schmooze (0.2.0).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions