String Like Array

Published by Theldoria in

Extend the String class so that you can call (almost) all functions available in instances of Array for instances of String.

In general, a string should be returned as the result of function calls:

 "123abc".first ➞ "1"

For to_a return an array of strings:

 "123abc".to_a ➞ ["1", "2", "3", "a", "b", "c"]

For functions returning an array of arrays, return an array of strings:

"foo".zip("bar") ➞ ["fb", "oa", "or"]

"abc".permutation(2) ➞ ["ab", "ac", "ba", "bc", "ca", "cb"]

"abc".product("fo") ➞ ["af", "ao", "bf", "bo", "cf", "co"]

Your implementation should be fair. That means I should be able to ask it what it supports (by calling respond_to?).

There is no test for all functions in an instance of Array. However, you should implement your solution in a way that allows you to support unforeseen functions (i.e. functions that are added to Array later).

Notes

  • There is no need to implement to_h.
  • There is no need to implement functions during runtime (e.g. define_method).
  • For functions that require a block, you can expect a block to be given. This means you do not have to process the special case of returning special enumerables.
  • To sove this you might want to leverage Ruby's ability to perform metaprogramming (see the Resources tab).
Watch a quick demo on how Edabit works.