Home > Enterprise >  define local/private structs in ruby
define local/private structs in ruby

Time:07-25

I want to define a struct which is local to a file/class. I.e., if I define struct foo in two different files, I want one to be applicable to file a, and one to file b.

Is that doable?

CodePudding user response:

Just as idea: you can use modules or inner classes

module A
  MyStruct = Struct.new(:x)
end

module B
  MyStruct = Struct.new(:x)
end

or

class A
  MyStruct = Struct.new(:x)
end

class B
  MyStruct = Struct.new(:x)
end

This way you can use your structs independently as A::MyStruct and B::MyStruct

CodePudding user response:

Just assign the struct class to a local variable (i.e. don't give it a class name).

my_struct = Struct.new(:x)

Caveat

You can't use the struct definition inside classes/modules/functions/methods in the same file.

my_struct = Struct.new(:x)

# This works
my_instance = my_struct.new(123)

class Foo
  def foo
    # This does NOT work
    my_struct.new(123)
  end
end
  • Related