The .last allready is a method for collections like an Array.
But I think I see what you want, a generic method for both Array and String.
and it needs to be able to accept both a various number of arguments (Array of args)
as well as an Array itself.
If you study the results below you see what goes wrong with the various versions
You would have to add the .last method to String but then you are still in trouble
when you pass an Array, so take a look at the last solution.
It first flattens any arrays and gives the .last element,
then it looks at the class of the last element, in case it's a String
it [-1] returns the last character, otherwise just the number
Arguments other than String or Array that don't support .last will still give an error
I run this from my editor, not irb so I use p here to do some simple debugging.
Why p instead of puts ? Because it inspects an object and prints arrays on one line.
The [__LINE__] construct is to print the linenumber to see which results you are seeing
I left them in place so that you can try this simple debugging technique.
You would better call this method otherswise (eg last_of) to avoid confusions with the .last method in some classes.
p [__LINE__,[1, 2, 3].last] # 3
def last(x)
x[-1]
end
p [__LINE__,last([1, 2, 3])] # 3
#p last(1, 2, 3) # wrong number of arguments (3 for 1) (ArgumentError)
p [__LINE__, last("a string")] # g
def last(*x)
p [__LINE__, x]
x[-1]
end
p [__LINE__, last([1, 2, 3])] # [1, 2, 3]
p [__LINE__, last(1, 2, 3)] # 3
p [__LINE__, last("a string")] # "a string"
def last *x
e = x.flatten.last # flatten any Arrays
case e
when String
e[-1]
when Fixnum
e
end
end
p [__LINE__, last([1, 2, 3])] # 3
p [__LINE__, last(1, 2, 3)] # 3
p [__LINE__, last("a string")] # "g"
p [__LINE__, last(["a string"])] # "g"
lastis a predefined method inrails, change the name to something elselast(1, 2, 3) # => 3