patternrubyMinor
Find the last element of a list
Viewed 0 times
lasttheelementfindlist
Problem
Find the last element of a list from codewars.com
Example:
I completed this kata several times tonight. My current answer is a mashup of several other people's solutions.
-
Other suggestions?
Example:
last( [1,2,3,4] ) # => 4
last( "xyz" ) # => z
last( 1,2,3,4 ) # => 4I 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
endSolution
-
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.
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.
Context
StackExchange Code Review Q#75315, answer score: 4
Revisions (0)
No revisions yet.