Reputation: 7326
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
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
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