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

  • Home
  • SEARCH
  • 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

Ask A Question

Stats

  • Questions 493k
  • Answers 493k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer You could use Class.forName to load different classes depending on… May 16, 2026 at 10:46 am
  • Editorial Team
    Editorial Team added an answer The problem is that you cannot overload operator== like this:… May 16, 2026 at 10:46 am
  • Editorial Team
    Editorial Team added an answer The question's not so well worded. I can't think of… May 16, 2026 at 10:46 am

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Related Questions

I'm using the Ruby SVN bindings built with SWIG. Here's a little tutorial. When
I have built a very simple blog application using Ruby on Rails. New to
Using module_eval, my code allows me to dynamically create and add new methods to
I would like to add some debugs for my simple ruby functions and I
So, I wrote a quick thread example for myself, using the ruby docs for
I'm trying to get started with Twilio's REST API using the rubygem twilio-ruby ,
I am using ActiveScaffold in a Ruby on Rails app, and to save space
I'm using the Ruby official Ruby C interface and am not able to bzip
I want to create a login page, it can easy implement using Ruby on
I am writing a web based application using Ruby on Rails. In one of

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.