Create or rename method in Rails

Viewed 100

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

2 Answers

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.

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

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

  ...
end
Related