ӧѧ ѧܧ wrote:
> I would like to create a new general delimiter.
> 
> ----------  Background
> 
> Suppose you have created a specific data type which is a combination of
> various other native data types, such as strings and numbers.
> 
> Suppose that these are needed throughout your code, so you would like to
> quickly express them.
> 
> I have found one way to do this,
> 
> class WhatEver
>    .
>    .
>    .
> end
> 
> def we(o)
>   WhatEver.new(o)
> end
> 
> so that I can type
> 
>          a = we " This 73  brqx "
> 
> in my code as a shorthand for
> 
>          a = WhatEver.new "This 73 brqx"
> 
> ---------  Question
> 
> I think code would be more readable if I could type,
> 
>          a = %e "This 73 brqx"
> 
> -> I know there is metaprogramming in Ruby, and Ruby is quite flexible
> -> The question is...  Is this possible?  Where is %q, for example,
> defined?  It does not appear to be a method of String or Object or
> Kernel
> -> OK, so let's say it's something in C.  Where would I modify the C to
> get this if I would want to?

%q is part of Ruby's syntax and not a method. You can't modify how Ruby 
code is parsed via metaprogramming, the only way possible is to modify 
Ruby's C sources before you compile Ruby.

What is possible is to "absuse" the special ` method (you know, it's 
usually for executing system commands). Although `cmd` looks like a 
literal, it's actually the method Kernel#` and as such it can be 
overriden:

irb(main):001:0> def `(str)
irb(main):002:1> puts str
irb(main):003:1> end
=> nil
irb(main):004:0> `abc`
abc
=> nil
irb(main):005:0>

Note that it's possible to do limit the redefined ` to a namespace:

irb(main):001:0> class Foo
irb(main):002:1> def `(str)
irb(main):003:2> puts "Got #{str}."
irb(main):004:2> end
irb(main):005:1> def bar
irb(main):006:2> `echo hello`
irb(main):007:2> end
irb(main):008:1> end
=> nil
irb(main):009:0> `echo hello`
=> "hello\n"
irb(main):010:0> Foo.new.bar
Got echo hello.
=> nil
irb(main):011:0> module Bar
irb(main):012:1> class << self
irb(main):013:2> def `(str)
irb(main):014:3> puts "Got #{str}."
irb(main):015:3> end
irb(main):016:2> end
irb(main):017:1> `echo hello`
irb(main):018:1> end
Got echo hello.
=> nil
irb(main):019:0> `echo hello`
=> "hello\n"
irb(main):020:0>

I've never seen this anywhere, so I suppose it's considered bad style.

Marvin
-- 
Posted via http://www.ruby-forum.com/.