Find the last element of a list Find the last element of a list from codewars.com


  Example:

last( [1,2,3,4] ) # =&gt; 4

last( "xyz" ) # =&gt; z

last( 1,2,3,4 ) # =&gt; 4



I completed this kata several times tonight.  My current answer is a mashup of several other people's solutions. 


I do not understand why I cant change .respond_to?(:index) into .is_a? Array
Should I use ternary operators in Ruby?
Other suggestions?

def last (*arg, arg_last)
  arg_last.respond_to?(:index) ? arg_last[-1] : arg_last
end
Your input might be a String or an Array. Both of these support the :index method, so foo[-1] will give the last character of a string or the last element of an array. But if you test for it being an array, the solution won't work for strings when it otherwise would.
I don't think there's anything wrong with using ternary operators in ruby, as long as all three 'elements' are fairly short. More concise code is easier to read. See the Ruby Style Guide at https://github.com/bbatsov/ruby-style-guide#ternary-operator.