Skip to content

Instantly share code, notes, and snippets.

@Bodacious
Created February 5, 2015 16:07
Show Gist options
  • Select an option

  • Save Bodacious/ed8c6c8e479b780689a0 to your computer and use it in GitHub Desktop.

Select an option

Save Bodacious/ed8c6c8e479b780689a0 to your computer and use it in GitHub Desktop.
Ruby core extension for adding items conditionally to Arrays
class Array
# Inserts an object to the Array if condition is true
#
# object - The object to insert.
# condition - The condition to evaluate.
#
# Example:
#
# = content_tag(:div, class: ["user-username"].insert_if("active", @user.active)) do
# = @user.username
#
# Returns the same Array
def insert_if(object, condition)
tap { |array| array << object if condition }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment