Adding members to Ruby objects dynamically

Adding members to Ruby objects dynamically

If you want to dynamically add a member to a Ruby object, use the hash/array brackets and symbol (:user_id) as shown in the iRb session below. As you can see the dot notation will not work.

bash

  1. >> d = AccessMode.find(1)
  2. => #<AccessMode id: 1, device_id: 31218, mode: "dialup", timestamp: "2007-12-25 15:52:55">
  3. >> d[:user_id] = 5
  4. => 5
  5. >> d
  6. => #<AccessMode id: 1, device_id: 31218, mode: "dialup", timestamp: "2007-12-25 15:52:55">
  7. >> d.user_id
  8. => 5
  9. >> d.user_id = 6
  10. => 6
  11. >> d.session_id = 10
  12. NoMethodError: undefined method `session_id=' for #<AccessMode:0x58dace8>
  13. from C:/chirag no backup/haloror/vendor/rails/activerecord/lib/active_record/attribute_methods.rb:251:in `method_missing'
  14. from (irb):23
Share