1

How to add method, or rename method name?

I have code like this:

"X Y".split().first => X
"X Y".split().last => Y

In a string, there is always only one space.

I'd like to change this to:

"X Y".a  => X
"X Y".b  => Y

How to achieve this goal? Ryby 2.7, Rails 6

Regards

sssebaaa
  • 75
  • 1
  • 9

2 Answers2

1

Not sure why you would want to do this in the first place since you can get character at any place in a string with:

"abc".chr == "a"
"abc"[0] == "a"
"abc"[-1] == "c"

If you really want to add methods to a string create a module:

module MyStringExtensions
  def a
    chr
  end

  def b
    self[-1]
  end
end

You can then extend string instances with the module to augment them:

"abc".extend(MyStringExtensions).a # "a"

You can also monkeypatch the String class if you really want to:

String.include(StringExtensions)

Using a module is generally better then reopening someone elses class as it gives a better stack trace for debugging.

max
  • 96,212
  • 14
  • 104
  • 165
  • You can also say `s = 'abc'; def s.a; split.first; end` to add a singleton method and then `s.a` does The Right Thing while leaving other strings alone. Curious as to what the real goal is though. – mu is too short Aug 11 '21 at 17:58
0

You could create extensions methods for String class like described here.

class String
  def a
    self.split().first
  end

  ...
end