Recently I found a way around this. I wanted to create a method in the array class with an optional parameter, to keep or discard elements in the array.
The way I simulated this was by passing an array as the parameter, and then checking if the value at that index was nil or not.
class Array def ascii_to_text(params) param_len = params.length if param_len > 3 or param_len < 2 then raise "Invalid number of arguments #{param_len} for 2 || 3." end bottom = params[0] top = params[1] keep = params[2] if keep.nil? == false if keep == 1 self.map{|x| if x >= bottom and x <= top then x = x.chr else x = x.to_s end} else raise "Invalid option #{keep} at argument position 3 in #{p params}, must be 1 or nil" end else self.map{|x| if x >= bottom and x <= top then x = x.chr end}.compact end end end
Trying out our class method with different parameters:
array = [1, 2, 97, 98, 99] p array.ascii_to_text([32, 126, 1]) # Convert all ASCII values of 32-126 to their chr value otherwise keep it the same (That's what the optional 1 is for)
output: ["1", "2", "a", "b", "c"]
Okay, cool that works as planned. Now let's check and see what happens if we don't pass in the the third parameter option (1) in the array.
array = [1, 2, 97, 98, 99] p array.ascii_to_text([32, 126]) # Convert all ASCII values of 32-126 to their chr value else remove it (1 isn't a parameter option)
output: ["a", "b", "c"]
As you can see, the third option in the array has been removed, thus initiating a different section in the method and removing all ASCII values that are not in our range (32-126)
Alternatively, we could had issued the value as nil in the parameters. Which would look similar to the following code block:
def ascii_to_text(top, bottom, keep = nil) if keep.nil? self.map{|x| if x >= bottom and x <= top then x = x.chr end}.compact else self.map{|x| if x >= bottom and x <= top then x = x.chr else x = x.to_s end} end