Vitalii Elenhaupt
Vitalii Elenhaupt

Reputation: 7326

Is there a way to define new literal in Ruby?

For example, here is a list of defined ruby literals. Does ruby give us a way to define new "custom" one?

[Updated] Purpose is to simplify a process of object instantiation. For example if I want to create object based on some dynamic language i'd like to have something like this:

obj = @|
  rule1 = "..."
  rule2 = "..."

  value1 = "..."
  value2 = "..."
|

instead of

hash = {rule1: "...", rule2: "...", value1: "...", value2: "..."}
obj = MyObj.new(hash)

Upvotes: 3

Views: 458

Answers (3)

Stefan
Stefan

Reputation: 114208

i'd like to have something like this:

obj = @|
  rule1 = "..."
  rule2 = "..."

  value1 = "..."
  value2 = "..."
|

That’s not possible, but you can build something quite similar:

obj = MyObj.build {
  rule1 'foo'
  rule2 'bar'

  value1 'baz'
  value2 'qux'
}

obj #=> #<MyObj:0x007fcd7d01ee90 @rule1="foo", @rule2="bar", @value1="baz", @value2="qux">

Implementation:

class Builder
  def initialize(obj)
    @obj = obj
  end

  def method_missing(name, value)
    @obj.public_send("#{name}=", value)
  end
end

class MyObj
  attr_accessor :rule1, :rule2, :value1, :value2

  def self.build(&block)
    new.tap { |obj| Builder.new(obj).instance_eval(&block) }
  end
end

Upvotes: 5

sawa
sawa

Reputation: 168199

If you mean in Ruby, you can't. But if you mean in C, you can.

Upvotes: 0

J&#246;rg W Mittag
J&#246;rg W Mittag

Reputation: 369526

No. There is no way to change the syntax of Ruby in a Ruby program.

If you want to define a new literal, you have to propose it on the Ruby bugtracker, convince matz that it is a good idea, then convince the developers of YARV, JRuby, Rubinius, IronRuby, MRuby, MagLev, Topaz, Cardinal, tinyrb, MacRuby, RubyMotion, BlueRuby, Opal, XRuby, Ruby.NET, Alumina, SmallRuby, or whatever implementation you care about to implement it, then wait for the community to update to newer versions of the implementations.

Upvotes: 8

Related Questions