Skip to content

Instantly share code, notes, and snippets.

@noelrappin
Last active September 7, 2023 09:24
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save noelrappin/a046996a3e9e5d5034533f5a37b349b8 to your computer and use it in GitHub Desktop.
Save noelrappin/a046996a3e9e5d5034533f5a37b349b8 to your computer and use it in GitHub Desktop.
# Prompt:
What’s your most elegant Ruby code that does this:
* takes an array of strings and a target string
* if the target string is not in the array, return the array
* if the target string is in the array, return the array with the target string moved from its position to the end of the array.
What’s your most elegant Ruby code that does this:
* takes an array of strings and a target string
* if the target string is not in the array, return the array
* if the target string is in the array, return the array with the target string moved from its position to the end of the array.
Later note: I don't care if the initial array is mutated or not
Also, you can assume the target only appears once.
Of the first six, in random order (style and naming normalized)
* One of these is my original try
* One is ChatGPT
* Three of them are submissions (don’t peek)
* One is ChatGPT after I asked for a refinement
# Option 1
def move_target_to_end(arr, target)
if arr.include?(target)
arr.delete(target)
arr << target
else
arr
end
end
# Option 2
def move_target_to_end(arr, target)
return arr unless arr.include?(target)
(arr - [target]) << target
end
# Option 3
def move_target_to_end(arr, target)
index = arr.index(target)
if index.nil?
return arr
end
arr.delete_at(index)
arr + [target]
end
# Option 4
def move_target_to_end(arr, target)
result = arr.dup
result.delete(target) ? result.push(target) : result
end
# Option 5
def move_target_to_end(arr, target)
partial = array - [target]
return array if partial == target
partial + [target]
end
# Option 6
def move_target_to_end(arr, target)
arr.include?(target) ? arr.push(arr.delete(target)) : arr
end
# Options added after initial post
# Option 7
def move_target_to_end(arr, target)
arr.tap { |a| a << a.delete(target) }.compact
end
# Option 8
def move_target_to_end(arr, target)
arr.tap { arr.delete(target) && arr.push(target }
end
# Option 9
def move_target_to_end(arr, target)
arr.delete(target) ? arr << target : arr
end
# Option 10
def move_target_to_end(arr, target)
arr.find_index(target)&.then { arr.append(arr.delete_at(_1)) } || arr
end
# Option 11
def move_target_to_end(arr, target)
arr.sort_by.with_index { target == _1 ? arr.size : _2 }
end
# Option 12
def move_target_to_end(arr, target)
arr.partition { _1 != target }.flatten
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment