Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 482 Vote(s) - 3.42 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to dynamically call accessor methods in Ruby

#1
Regardless of whether it's good practice or not, how can I dynamically call accessor methods in Ruby?

Here's an example class:

class Test_Class
attr_accessor :a, :b
end

I can use the Object.send method to read the variable...

instance.a = "value"
puts( instance.send( "a" ) )
# => value

But I'm having a hard time trying to write to it. These throw "wrong number of arguments (1 for 0) (ArgumentError)"

instance.send("a", "value")
and

instance.method("a").call("value")

Please help me StackOverflow!
Reply

#2
You can also directly access instance variables of an object using `instance_variable_*` functions:

instance = Test_Class.new # => #<Test_Class:0x12b3b84>

# instance variables are lazily created after first use of setter,
# so for now instance variables list is empty:
instance.instance_variables # => []

instance.instance_variable_set(:@a, 123) # => 123
instance.a # => 123
instance.instance_variables # => ["@a"]
instance.instance_variable_get("@a") # => 123

Reply

#3
I am not a ruby expert, but I think that you could do:

instance.send("a=", "value")

Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through