Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 652067
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T22:13:52+00:00 2026-05-13T22:13:52+00:00

Question: Using Ruby it is simple to add custom methods to existing classes, but

  • 0

Question:
Using Ruby it is simple to add custom methods to existing classes, but how do you add custom properties? Here is an example of what I am trying to do:

myarray = Array.new();
myarray.concat([1,2,3]);
myarray._meta_ = Hash.new();      # obviously, this wont work
myarray._meta_['createdby'] = 'dreftymac';
myarray._meta_['lastupdate'] = '1993-12-12';

## desired result
puts myarray._meta_['createdby']; #=> 'dreftymac'
puts myarray.inspect()            #=> [1,2,3]

The goal is to construct the class definition in such a way that the stuff that does not work in the example above will work as expected.

Update: (clarify question) One aspect that was left out of the original question: it is also a goal to add “default values” that would ordinarily be set-up in the initialize method of the class.

Update: (why do this) Normally, it is very simple to just create a custom class that inherits from Array (or whatever built-in class you want to emulate). This question derives from some “testing-only” code and is not an attempt to ignore this generally acceptable approach.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-13T22:13:53+00:00Added an answer on May 13, 2026 at 10:13 pm

    Recall that in Ruby, you do not have access to attributes (instance variables) outside of that instance. You only have access to an instance’s public methods.

    You can use attr_accessor to create a method for a class that acts as a property as you describe:

    irb(main):001:0> class Array
    irb(main):002:1>  attr_accessor :_meta_
    irb(main):003:1> end
    => nil
    irb(main):004:0> 
    irb(main):005:0* x = [1,2,3]
    => [1, 2, 3]
    irb(main):006:0> x._meta_ = Hash.new
    => {}
    irb(main):007:0> x._meta_[:key] = 'value'
    => "value"
    irb(main):008:0> 
    

    For a simple way to do a default initialization for an accessor, we’ll need to basically reimplement attr_accessor ourselves:

    class Class
      def attr_accessor_with_default accessor, default_value
        define_method(accessor) do
          name = "@#{accessor}"
          instance_variable_set(name, default_value) unless instance_variable_defined?(name)
          instance_variable_get(name)
        end
    
        define_method("#{accessor}=") do |val|
          instance_variable_set("@#{accessor}", val)
        end
      end
    end
    
    class Array
        attr_accessor_with_default :_meta_, {}
    end
    
    x = [1,2,3]
    x._meta_[:key] = 'value'
    p x._meta_
    
    y = [4,5,6]
    y._meta_[:foo] = 'bar'
    p y._meta_
    

    But wait! The output is incorrect:

    {:key=>"value"}
    {:foo=>"bar", :key=>"value"}
    

    We’ve created a closure around the default value of a literal hash.

    A better way might be to simply use a block:

    class Class
      def attr_accessor_with_default accessor, &default_value_block
        define_method(accessor) do
          name = "@#{accessor}"
          instance_variable_set(name, default_value_block.call) unless instance_variable_defined?(name)
          instance_variable_get(name)
        end
    
        define_method("#{accessor}=") do |val|
          instance_variable_set("@#{accessor}", val)
        end
      end
    end
    
    class Array
        attr_accessor_with_default :_meta_ do Hash.new end
    end
    
    x = [1,2,3]
    x._meta_[:key] = 'value'
    p x._meta_
    
    y = [4,5,6]
    y._meta_[:foo] = 'bar'
    p y._meta_
    

    Now the output is correct because Hash.new is called every time the default value is retrieved, as opposed to reusing the same literal hash every time.

    {:key=>"value"}
    {:foo=>"bar"}
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am using Ruby on Rails, but I think this question could be applied
Rails: 3.0.3 Ruby: 1.9.2 Trying to deserialize a very simple object using YAML.load or
My question it's very simple, but I don't find a solution. I'm using: Rails
A simple question for most regex experts I know, but I'm trying to return
I'm using Ruby script and the mail gem to send emails. Question - How
Note: I had another similar question about how to GZIP data using Ruby's zlib
Question: How can I document Ruby code using Doxygen? Disclaimer: I know ruby already
I typed up a simple Ruby code for a tutorial question, as shown below.
This might be a simple question to answer, but I couldn't find the answer.
Using module_eval, my code allows me to dynamically create and add new methods to

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.