### Install Finishing Moves via Command Line
Source: https://github.com/battlebrisket/finishing_moves/blob/master/README.md
Install the gem directly using the RubyGems command line interface.
```bash
gem install 'finishing_moves'
```
--------------------------------
### Install Finishing Moves via Gemfile
Source: https://github.com/battlebrisket/finishing_moves/blob/master/README.md
Add the gem to your project's Gemfile to include it as a dependency.
```ruby
gem 'finishing_moves'
```
--------------------------------
### Login approval process using cascade
Source: https://github.com/battlebrisket/finishing_moves/wiki/Kernel
A contrived example demonstrating how cascade handles a login process with multiple exit points using break.
```ruby
cascade do
logged_in = false
# not doing anything if they didn't provide creds
break if params['username'].nil? || params['password'].nil?
# ok, got creds, do they exist?
user = User.find_by username: params['username']
# does the user exist?
break if user.nil?
# does the password match?
break if user.validate_password(params['password'])
# maybe the user account is banned?
break if user.banned?
# everything looks good, let's do it
login user
logged_in = true
end
if logged_in
# additional follow-up steps for authenticated users
else
# display error message, log the failed attempt, whatever
end
```
--------------------------------
### Define Pokedex with levels
Source: https://github.com/battlebrisket/finishing_moves/wiki/Enumerable
Setup for demonstrating map/reduce operations on a collection of hashes.
```ruby
my_pokedex = [
{name: "Bulbasaur", level: 2},
{name: "Charmander", level: 2},
{name: "Squirtle", level: 2},
]
```
--------------------------------
### Define Pokemon class and collection
Source: https://github.com/battlebrisket/finishing_moves/wiki/Enumerable
Setup for demonstrating Enumerable mapping on a collection of objects.
```ruby
class Pokemon
attr_accessor :name
def initialize(n)
@name = n
end
end
your_pokedex = [
Pokemon.new("Bulbasaur"),
Pokemon.new("Charmander"),
Pokemon.new("Squirtle"),
]
```
--------------------------------
### Array#to_hash_keys(starting_value = 0, &block)
Source: https://github.com/battlebrisket/finishing_moves/wiki/Array
Converts an array into a hash where array elements become keys, with a specified starting value.
```APIDOC
## Array#to_hash_keys
### Description
Converts an array of items into a hash, with the array values becoming keys. The starting_value is assigned to each key.
### Parameters
- **starting_value** (Object) - Optional - The value assigned to each key. Defaults to 0.
- **block** (Proc) - Optional - A block to define the value for each key.
```
--------------------------------
### Define hash-based Pokedex
Source: https://github.com/battlebrisket/finishing_moves/wiki/Enumerable
Setup for demonstrating mapping on a collection of hashes.
```ruby
my_pokedex = [
{name: "Bulbasaur"},
{name: "Charmander"},
{name: "Squirtle"},
]
```
--------------------------------
### Array#to_indexed_hash(starting_key = 0)
Source: https://github.com/battlebrisket/finishing_moves/wiki/Array
Converts an array into a hash with integer keys starting from the provided index, incrementing by 1.
```APIDOC
## Array#to_indexed_hash
### Description
Converts an array into a hash where array elements are values and keys are integers. Raises ArgumentError if the starting_key is not an Integer.
### Parameters
- **starting_key** (Integer) - Optional - The starting integer for the index. Defaults to 0.
```
--------------------------------
### Array#to_hash_values(starting_key = 0, &block)
Source: https://github.com/battlebrisket/finishing_moves/wiki/Array
Converts an array into a hash where array elements are values. Keys are generated starting from starting_key, optionally using a block to define key increment logic.
```APIDOC
## Array#to_hash_values
### Description
Converts an array of items into a hash with the array elements stored as values. By default, the hash is numerically indexed starting from zero.
### Parameters
- **starting_key** (Integer/Object) - Optional - The starting value for the key index. Defaults to 0.
- **block** (Proc) - Optional - A block to define how the next key is calculated based on the current key.
### Example
```ruby
sages = ['Rauru', 'Saria', 'Darunia']
sages.to_hash_values(0) { |key| key + 3 }
# => {0=>"Rauru", 3=>"Saria", 6=>"Darunia"}
```
```
--------------------------------
### Array#to_hash_keys default usage
Source: https://github.com/battlebrisket/finishing_moves/wiki/Array
Converts an array into a hash where array elements are keys and the starting value is zero.
```ruby
sages = ['Rauru', 'Saria', 'Darunia', 'Princess Ruto', 'Impa', 'Nabooru', 'Zelda']
sages_hash = sages.to_hash_keys
# => {"Rauru"=>0, "Saria"=>0, "Darunia"=>0, "Princess Ruto"=>0, "Impa"=>0, "Nabooru"=>0, "Zelda"=>0}
```
--------------------------------
### Rails model association usage
Source: https://github.com/battlebrisket/finishing_moves/wiki/Kernel
Example of using nil_chain in a Rails context to safely access nested model attributes.
```ruby
# Model User has ZERO or more addresses, one of which is the primary.
# Model Address has a zip_code attribute.
user = User.find(9876)
nil_chain{ user.addresses.primary.zip_code }
# => returns nil if no addresses, or primary not set, otherwise returns zip_code
```
--------------------------------
### Array#to_hash_values default usage
Source: https://github.com/battlebrisket/finishing_moves/wiki/Array
Converts an array into a hash with numerical keys starting from zero.
```ruby
sages = ['Rauru', 'Saria', 'Darunia', 'Princess Ruto', 'Impa', 'Nabooru', 'Zelda']
sages_hash = sages.to_hash_values
# => {0=>"Rauru", 1=>"Saria", 2=>"Darunia", 3=>"Princess Ruto", 4=>"Impa", 5=>"Nabooru", 6=>"Zelda"}
```
--------------------------------
### Real-world usage in ReportsController
Source: https://github.com/battlebrisket/finishing_moves/wiki/Kernel
An example of using cascade within a Rails controller to determine the @category variable without creating an extra method.
```ruby
class ReportsController < ApplicationController
before_action :define_search_params, only: :run_report
# ...
def define_search_params
@report = params[:report].to_sym
# Set the report category, :medical or :drug
# 1. An :ongoing report is always in the :drug category
# 2. Otherwise default to :medical
# 3. :dismissal reports are always :medical (so we use the default)
# 4. Finally just use the params value, if it matches an allowable value
cascade do
if @report == :ongoing
@category = :drug
break
end
@category = :medical
break if @report == :dismissals
@category = params[:category] if params[:category].in? allowable_categories
end
end
end
```
--------------------------------
### Handling invalid UUID inputs with String#to_uuid
Source: https://github.com/battlebrisket/finishing_moves/wiki/String
Examples of inputs that trigger an ArgumentError, including non-hexadecimal characters, incorrect lengths, and random strings.
```ruby
# yolo is not found in hexadecimal
"c6cabb4a709a4a448114d2b02132yolo".to_uuid
# => ArgumentError: "c6cabb4a709a4a448114d2b02132yolo" is not a valid UUID
# too long, 33 characters
"a99fee17da4f45128f1dd482c686f1a49".to_uuid
# => ArgumentError: "a99fee17da4f45128f1dd482c686f1a49" is not a valid UUID
"some random string".to_uuid
# => ArgumentError: "some random string" is not a valid UUID
```
--------------------------------
### Attempting to map hash keys with shortcut
Source: https://github.com/battlebrisket/finishing_moves/wiki/Enumerable
Demonstrates the limitation of standard Ruby shortcuts when working with hash keys.
```ruby
my_pokedex.map(??????)
# => ["Bulbasaur", "Charmander", "Squirtle"]
```
--------------------------------
### String#keyify for hash keys
Source: https://github.com/battlebrisket/finishing_moves/wiki/String
Build a hash using keyified string values as keys.
```ruby
my_hash = {}
['Option A', 'Option B', 'Option C', 'Option D'].each do |opt|
my_hash[opt.keyify] = opt
end
my_hash
# => {:option_a=>"Option A", :option_b=>"Option B", :option_c=>"Option C", :option_d=>"Option D"}
```
--------------------------------
### String#keyify for identifiers
Source: https://github.com/battlebrisket/finishing_moves/wiki/String
Generate identifiers from user-provided strings.
```ruby
'Not a covered benefit'.keyify
# => :not_a_covered_benefit
"User's Duplicate Claim".keyify
# => :user_s_duplicate_claim
"Included in global amount/bundled".keyify
# => :included_in_global_amount_bundled
```
--------------------------------
### String#slugify usage
Source: https://github.com/battlebrisket/finishing_moves/wiki/String
Similar to keyify but returns a string and permits leading numbers.
```ruby
'FooBarBaz'.slugify
# => 'foo-bar-baz'
"Foo-Bar'Baz".slugify
# => 'foo-bar-baz'
'1234FooBAR'.slugify
# => '1234-foo-bar'
# Accepts Symbols
:FooBarBaz.slugify
# => 'foo-bar-baz'
# Also accepts static classes
Math::DomainError.slugify
# => 'math-error'
```
--------------------------------
### String#keyify comparison
Source: https://github.com/battlebrisket/finishing_moves/wiki/String
Use keyify to normalize user-entered data for consistent comparison.
```ruby
'John Doe'.keyify
# => :john_doe
'JOHN DOE'.keyify
# => :john_doe
'John Doe'.keyify == 'JOHN DOE'.keyify
# => true
"Ted O'Baxter".keyify == 'Ted O Baxter'.keyify
# => true
```
--------------------------------
### Object#same_as with custom classes
Source: https://github.com/battlebrisket/finishing_moves/wiki/Object
Shows how custom classes inherit same_as and rely on the to_s method for comparison.
```ruby
class User
attr_writer :handle
def handle
@handle || "faceless_one"
end
def to_s
handle.to_s
end
end
user = User.new
:faceless_one.same_as user
# => true
user.same_as :faceless_one
# => true
user.same_as 'faceless_one'
# => true
user.same_as 'FACELESS_ONE'
# => false
```
--------------------------------
### String#keyify! error handling
Source: https://github.com/battlebrisket/finishing_moves/wiki/String
The bang variant raises an ArgumentError if the result is an empty string.
```ruby
' '.keyify!
# => ArgumentError: " " cannot be keyified, no valid characters
'!@#$%^'.keyify!
# => ArgumentError: "!@#$%^" cannot be keyified, no valid characters
'12345678'.keyify!
# => ArgumentError: "12345678" cannot be keyified, no valid characters
```
--------------------------------
### Typecasting from Boolean and Nil
Source: https://github.com/battlebrisket/finishing_moves/wiki/Boolean-Typecasting
Converts boolean and nil values to integers or symbols. Note that NilClass#to_sym returns nil starting in v0.8.
```ruby
true.to_i
# => 1
true.to_sym
# => :true
false.to_i
# => 0
false.to_sym
# => :false
nil.to_i
# => 0
nil.to_sym
# => nil
```
--------------------------------
### Simplify map and reduce with Enumerable#key_map_reduce
Source: https://github.com/battlebrisket/finishing_moves/wiki/Enumerable
Using the finishing_moves extension to perform a one-step map/reduce operation.
```ruby
my_pokedex.key_map_reduce(:level, :+)
# => 6
```
--------------------------------
### Object#same_as case sensitivity
Source: https://github.com/battlebrisket/finishing_moves/wiki/Object
Demonstrates that standard case-sensitivity rules apply to the same_as method.
```ruby
:symbol.same_as :SYMBOL
# => false
:symbol.same_as 'SYMBOL'
# => still false
```
--------------------------------
### Conditional chaining pitfalls
Source: https://github.com/battlebrisket/finishing_moves/wiki/Kernel
Illustrates the complexity of manual nil checking compared to using nil_chain.
```ruby
b.c = nil
a.b.c.hello
# => NoMethodError: undefined method `hello' for nil:NilClass
a.b.c.hello unless b.c.nil? || b.c.empty?
# => nil
a.b = nil
# Now it's really getting ugly.
if !a.b.nil? && !a.b.empty?
a.b.c.hello unless b.c.nil? || b.c.empty?
end
# Imagine if we had a fourth association, or a fifth! The patterns, man!
```
--------------------------------
### String#keyify on classes
Source: https://github.com/battlebrisket/finishing_moves/wiki/String
Keyify works on static class declarations.
```ruby
Integer.keyify
# => :integer
Math::DomainError.keyify
# => :math_domain_error
```
--------------------------------
### Custom default values and complex expressions
Source: https://github.com/battlebrisket/finishing_moves/wiki/Kernel
Shows how to provide a default value or execute a method as a fallback when the chain fails.
```ruby
# without nil_chain
if my_hash[:foo]
# (by default, ruby returns nil when you request an unset key)
var = my_hash[:foo]
else
var = :default_value
end
# with nil_chain, we get a nice one liner
var = nil_chain(:default_value) { my_hash[:foo] }
# What if the default value is coming from somewhere else?
# What if we want to call a method directly on the hash?
# What if the ley lines are out of alignment!?
# No problem.
var = nil_chain(Geomancer.reset_ley_lines) { summon_fel_beast[:step_3].scry }
# => value of summon_fel_beast[:step_3].scry if it's set, or
# Geomancer.reset_ley_lines if it's not
```
--------------------------------
### nil_chain usage with hash keys
Source: https://github.com/battlebrisket/finishing_moves/wiki/Kernel
Shows how to safely access hash keys and call methods on the result using nil_chain.
```ruby
# without nil_chain, we check to make sure the key exists
if my_hash.has_key? :foo
my_hash[:foo].do_stuff
end
# with nil_chain, things look a lot cleaner
nil_chain{ my_hash[:foo].do_stuff }
# => result of my_hash[:foo].do_stuff, or nil
```
--------------------------------
### Map hash keys using Enumerable#key_map
Source: https://github.com/battlebrisket/finishing_moves/wiki/Enumerable
Using the finishing_moves extension to map hash keys directly.
```ruby
my_pokedex.key_map(:name)
# => ["Bulbasaur", "Charmander", "Squirtle"]
```
--------------------------------
### Custom block with Enumerable#key_map_reduce
Source: https://github.com/battlebrisket/finishing_moves/wiki/Enumerable
Using a custom block and initial value with key_map_reduce for added flexibility.
```ruby
my_pokedex.key_map_reduce(:level, 0) { |memo,lvl| memo + lvl }
# => 6
```
--------------------------------
### String#keyify normalization
Source: https://github.com/battlebrisket/finishing_moves/wiki/String
Normalizes strings into symbols for comparison or database keys.
```ruby
'FooBarBaz'.keyify
# => :foo_bar_baz
"Foo-Bar'Baz".keyify
# => :foo_bar_baz
'1234FooBAR'.keyify
# => :foo_bar
# Works with symbols as well
:FooBarBaz.keyify
# => :foo_bar_baz
```
--------------------------------
### Basic nil_chain usage for method calls
Source: https://github.com/battlebrisket/finishing_moves/wiki/Kernel
Demonstrates using nil_chain to safely call a method that might not exist on an object.
```ruby
# foobar may have a transmogrify method...or it may not! Doooooom!
# without nil_chain, we check to make sure the method exists
foobar.transmogrify if foobar.respond_to? :transmogrify
# with nil_chain, we just do it, and kick those nil ghosts in the teeth
nil_chain{ foobar.transmogrify }
# => result of foobar.transmogrify, or nil
```
--------------------------------
### String#keyify
Source: https://github.com/battlebrisket/finishing_moves/wiki/String
Normalizes a string into a codified symbol for comparison or data storage.
```APIDOC
## String#keyify
### Description
Normalizes a string by replacing non-alphanumerics with underscores, converting CamelCase to snake_case, stripping leading numbers/underscores, collapsing underscores, and converting to a lowercase symbol.
### Example
'FooBarBaz'.keyify # => :foo_bar_baz
'John Doe'.keyify # => :john_doe
### Bang Variant
`keyify!` performs the same action but raises an `ArgumentError` if the result is an empty string.
```
--------------------------------
### Map Pokemon names using symbol-to-proc shortcut
Source: https://github.com/battlebrisket/finishing_moves/wiki/Enumerable
Standard Ruby shortcut for calling a method on each element in a collection.
```ruby
your_pokedex.map(&:name)
# => ["Bulbasaur", "Charmander", "Squirtle"]
```
--------------------------------
### String#strip_all whitespace handling
Source: https://github.com/battlebrisket/finishing_moves/wiki/String
Always removes whitespace and newlines in addition to specified characters.
```ruby
"//// foo ////\n".strip_all('/')
# => 'foo'
```
--------------------------------
### Comparison of defined? and class_exists?
Source: https://github.com/battlebrisket/finishing_moves/wiki/Kernel
Contrasts the standard Ruby defined? method with the custom class_exists? method for conditional flow.
```ruby
defined?(SuperSaiyan)
# => nil
require 'super_saiyan'
defined?(SuperSaiyan)
# => 'constant'
if defined?(SuperSaiyan) == 'constant'
# Power up to level 4
# But after that obtuse if-statement, I'm just too tired
end
```
--------------------------------
### String#to_bool truthy and falsy values
Source: https://github.com/battlebrisket/finishing_moves/wiki/Boolean-Typecasting
Demonstrates how String#to_bool handles common truthy and falsy string representations in a case-insensitive manner.
```ruby
['1', 't', 'true', 'on', 'y', 'yes'].each do |true_string|
true_string.to_bool
# => true
true_string.upcase.to_bool
# => true
end
['0', 'f', 'false', 'off', 'n', 'no'].each do |false_string|
false_string.to_bool
# => false
false_string.upcase.to_bool
# => false
end
```
--------------------------------
### Standard map and reduce operation
Source: https://github.com/battlebrisket/finishing_moves/wiki/Enumerable
The standard Ruby approach to mapping and reducing a collection.
```ruby
my_pokedex.key_map(:level).reduce(0) { |memo,lvl| memo + lvl }
# => 6
```
--------------------------------
### Kernel#silently
Source: https://github.com/battlebrisket/finishing_moves/wiki/Kernel
Executes a block while rescuing all StandardError exceptions.
```APIDOC
## Kernel#silently
### Description
Executes a block and rescues all `StandardError` exceptions, returning a default value (nil by default) if an error occurs. It does not catch `Exception` or its descendants like `NoMemoryError` or `SystemExit`.
### Parameters
- **ret_val** (Object) - Optional - The value to return if an exception is caught. Defaults to nil.
- **block** (Proc) - Required - The code block to execute.
### Usage
```ruby
silently { raise "oops" }
# => nil
```
```
--------------------------------
### String#strip_all default behavior
Source: https://github.com/battlebrisket/finishing_moves/wiki/String
Strips leading and trailing dashes and underscores by default.
```ruby
'___foo___'.strip_all
# => 'foo'
'---foo---'.strip_all
# => 'foo'
```
--------------------------------
### Array#to_sym_loose usage and comparison
Source: https://github.com/battlebrisket/finishing_moves/wiki/Array
Demonstrates the difference between the strict and loose conversion methods. The loose variant ignores elements lacking a #to_sym method, such as integers or regex objects.
```ruby
test = ['String1', 'string2', :baz, 1, {bat: 'bat'}, /hay/]
test.to_sym_strict
# => NoMethodError: undefined method `to_sym' for 1:Fixnum
test.to_sym_loose
# => [:String1, :string2, :baz, 1, {bat: 'bat'}, /hay/]
test
# => ['String1', 'string2', :baz, 1, {bat: 'bat'}, /hay/]
```
--------------------------------
### Rails view helper usage
Source: https://github.com/battlebrisket/finishing_moves/wiki/Kernel
Using nil_chain to set default values for form inputs in Rails views.
```ruby
select_tag :date_field,
options_for_select(@dropdown_date_field, nil_chain{params[:date_field]} )
# => Sets the selected option in the dropdown if the :date_field parameter exists
```
--------------------------------
### Kernel#class_exists? usage
Source: https://github.com/battlebrisket/finishing_moves/wiki/Kernel
Demonstrates using class_exists? with symbols to return a boolean result.
```ruby
class_exists? :Symbol
# => true
class_exists? :Symbology
# => false, unless you're Dan Brown
class_exists? :Rails
# => true in a Rails app
```
--------------------------------
### Map hash keys using block notation
Source: https://github.com/battlebrisket/finishing_moves/wiki/Enumerable
Standard Ruby approach to extracting values from a collection of hashes.
```ruby
my_pokedex.map { |p| p[:name] }
# => ["Bulbasaur", "Charmander", "Squirtle"]
```
--------------------------------
### Map Pokemon names using block notation
Source: https://github.com/battlebrisket/finishing_moves/wiki/Enumerable
Standard Ruby approach to extracting names from a collection of objects.
```ruby
your_pokedex.map { |p| p.name }
# => ["Bulbasaur", "Charmander", "Squirtle"]
```
--------------------------------
### Hash#delete! with missing key
Source: https://github.com/battlebrisket/finishing_moves/wiki/Hash
Demonstrates that the hash remains unaltered if the specified key is not found.
```ruby
power_rangers.delete! :radiant_orchid
# => { :red => 'Jason Lee Scott', :blue => 'Billy Cranston' }
# It probably would've triggered if I included Kimberly
```
--------------------------------
### Kernel#class_exists? constant vs symbol
Source: https://github.com/battlebrisket/finishing_moves/wiki/Kernel
Shows that class_exists? requires a symbol or string, as passing an undefined constant will raise a NameError.
```ruby
class_exists? DefinitelyFakeClass
# => NameError: uninitialized constant DefinitelyFakeClass
class_exists? :DefinitelyFakeClass
# => false (at least it better be; if you *actually* use this name, I will find you...)
```
--------------------------------
### Object#not_nil? usage
Source: https://github.com/battlebrisket/finishing_moves/wiki/Object
A more readable alternative to !nil?.
```ruby
nil.not_nil?
# => false
'foobar'.not_nil?
# => true
```
--------------------------------
### String#to_bool empty string handling
Source: https://github.com/battlebrisket/finishing_moves/wiki/Boolean-Typecasting
Shows that empty strings or strings containing only whitespace evaluate to false.
```ruby
["", " ", " ", " "].each do |empty_string|
empty_string.to_bool
# => false
end
```
--------------------------------
### Object#same_as
Source: https://github.com/battlebrisket/finishing_moves/wiki/Object
Normalizes both sides of a comparison into strings using to_s and compares them for equality.
```APIDOC
## Object#same_as
### Description
Comparison operator that normalizes both sides into strings, then runs them over `==`. The comparison will work on any class that has a `to_s` method defined on it.
### Signature
`same_as(other)`
### Example
```ruby
:foobar.same_as 'foobar' # => true
'1'.same_as 1 # => true
```
```
--------------------------------
### Formatting a UUID string with String#to_uuid
Source: https://github.com/battlebrisket/finishing_moves/wiki/String
Demonstrates converting a dash-less UUID string back into the standard UUID display format.
```ruby
require 'securerandom'
str = SecureRandom.uuid
# => "cab93178-ba44-438c-85b1-49fed89e8a6f"
unformatted = str.delete('-')
# => "cab93178ba44438c85b149fed89e8a6f"
unformatted.to_uuid
# => "cab93178-ba44-438c-85b1-49fed89e8a6f"
```
--------------------------------
### String#slugify
Source: https://github.com/battlebrisket/finishing_moves/wiki/String
Normalizes a string into a URL-friendly slug format.
```APIDOC
## String#slugify
### Description
Similar to `keyify`, but uses dashes instead of underscores, permits leading numbers, and returns a String instead of a Symbol.
### Example
'FooBarBaz'.slugify # => 'foo-bar-baz'
'1234FooBAR'.slugify # => '1234-foo-bar'
### Bang Variant
`slugify!` performs the same action but raises an `ArgumentError` if the result is an empty string.
```
--------------------------------
### Rails controller parameter handling
Source: https://github.com/battlebrisket/finishing_moves/wiki/Kernel
Using nil_chain to safely handle optional parameters in a Rails controller action.
```ruby
# Somewhere in a random rails controller...
def search
case nil_chain { params[:case_state].downcase }
when 'open' then filter_only_open
when 'closed' then filter_only_closed
when 'invalid' then filter_only_invalid
when 'withdrawn' then filter_only_withdrawn
when 'canceled' then filter_only_canceled
end
# => apply a case state filter, or do nothing
end
```
--------------------------------
### String#strip_all with custom characters
Source: https://github.com/battlebrisket/finishing_moves/wiki/String
Strips specific characters provided as an argument, processed as a regex group.
```ruby
'__-_--foo--_-__'.strip_all
# => 'foo'
'123foo123'.strip_all('321')
# => 'foo'
'xXxXfooXxXx'.strip_all('XYZx')
# => 'foo'
```
--------------------------------
### String#strip_all case sensitivity
Source: https://github.com/battlebrisket/finishing_moves/wiki/String
Demonstrates that strip_all is case-sensitive.
```ruby
'ABCfooABC'.strip_all('abc')
# => 'ABCfooABC'
```
--------------------------------
### String#replace_whitespace
Source: https://github.com/battlebrisket/finishing_moves/wiki/String
Replaces all whitespace with a provided string.
```ruby
'1 2 3 4 5'.replace_whitespace('+')
# => '1+2+3+4+5'
```
--------------------------------
### String#newline_to with dedupe
Source: https://github.com/battlebrisket/finishing_moves/wiki/String
Chaining newline_to, strip_all, and dedupe for cleaning messy inputs.
```ruby
# note that we have a mix of newlines and commas
"\n\n10001\n10002\n10003,\n10004\n\n10005,,10006\n".newline_to(',').strip_all(',').dedupe(',')
# => "10001,10002,10003,10004,10005,10006"
```
--------------------------------
### String#newline_to with strip_all
Source: https://github.com/battlebrisket/finishing_moves/wiki/String
Chaining newline_to with strip_all to clean up leading and trailing characters.
```ruby
"\n\n10001\n10002\n10003\n10004\n10005\n10006\n".newline_to(',').strip_all(',')
# => "10001,10002,10003,10004,10005,10006"
```
--------------------------------
### String#newline_to default behavior
Source: https://github.com/battlebrisket/finishing_moves/wiki/String
Converts various newline styles into a single space by default.
```ruby
# Handles all the different break styles, just like nl2br
"Let's play Global Thermonuclear War.\n\rA strange game.\n\nThe only winning move is not to play.\r\nHow about a nice game of chess?\r".newline_to
# => "Let's play Global Thermonuclear War. A strange game. The only winning move is not to play. How about a nice game of chess? "
```
--------------------------------
### Boolean Conversion Methods
Source: https://github.com/battlebrisket/finishing_moves/wiki/Boolean-Typecasting
Methods to convert Boolean and Nil values to Integers or Symbols.
```APIDOC
## Boolean and Nil Conversion Methods
### Methods
- **TrueClass#to_i**: Returns 1.
- **TrueClass#to_sym**: Returns :true.
- **FalseClass#to_i**: Returns 0.
- **FalseClass#to_sym**: Returns :false.
- **NilClass#to_i**: Returns 0.
- **NilClass#to_sym**: Returns nil.
```
--------------------------------
### String#strip_all
Source: https://github.com/battlebrisket/finishing_moves/wiki/String
An enhanced version of the standard strip method that removes specified leading and trailing characters, including regex ranges.
```APIDOC
## String#strip_all
### Description
Removes specified leading and trailing characters from a string. Supports regex ranges like '0-9', 'a-z', and 'A-Z'. Also provides `lstrip_all` and `rstrip_all` variants, with corresponding bang methods for in-place modification.
### Parameters
- **chars** (String) - Optional - The characters to strip. Defaults to '-' and '_'.
```
--------------------------------
### Array#to_hash_values with block
Source: https://github.com/battlebrisket/finishing_moves/wiki/Array
Uses a block to define custom key increment logic.
```ruby
sages_hash = sages.to_hash_values(0) { |key| key + 3 }
# => {0=>"Rauru", 3=>"Saria", 6=>"Darunia", 9=>"Princess Ruto", 12=>"Impa", 15=>"Nabooru", 18=>"Zelda"}
```
--------------------------------
### Simplified conditional chaining with nil_chain
Source: https://github.com/battlebrisket/finishing_moves/wiki/Kernel
Shows how nil_chain replaces complex conditional logic for nested object calls.
```ruby
nil_chain{ a.b.c.hello }
# => output "Hello, world!" or nil
a = nil
nil_chain{ a.b.c.hello }
# => still just nil
```
--------------------------------
### Custom return value in CSV generation
Source: https://github.com/battlebrisket/finishing_moves/wiki/Kernel
Demonstrates providing a custom return value ('N/A') to nil_chain when a field is missing.
```ruby
CSV.generate do |csv|
@records.each do |record| # each record represents a single line in the CSV
values = []
csv_fields_in_order.each do |field|
values << nil_chain('N/A') { record.send(field) }
# respond with a pretty value when the field is empty or invalid
end
csv << values
end
end
```
--------------------------------
### String#dedupe with strip_all
Source: https://github.com/battlebrisket/finishing_moves/wiki/String
Combine dedupe with strip_all to remove leading or trailing characters.
```ruby
'/crazy//concatenated////file/path/'.dedupe('/')
# => '/crazy/concatenated/file/path/'
'/crazy//concatenated////file/path/'.dedupe('/').strip_all('/')
# => 'crazy/concatenated/file/path'
```
--------------------------------
### Object#is_not_a? usage
Source: https://github.com/battlebrisket/finishing_moves/wiki/Object
An inversion of the is_a? method for more natural reading.
```ruby
a = [1,2,3]
a.is_not_a? Array
# => false
a.is_not_a? Hash
# => true
```
--------------------------------
### String#nl2br
Source: https://github.com/battlebrisket/finishing_moves/wiki/String
Converts various newline formats into HTML break tags.
```APIDOC
## String#nl2br
### Description
Converts newlines (\n, \r, \r\n, \n\r) into `
\n` tags.
### Example
"\n".nl2br # => "
\n"
"\r\n".nl2br # => "
\n"
```
--------------------------------
### Array#to_hash_values with complex keys
Source: https://github.com/battlebrisket/finishing_moves/wiki/Array
Demonstrates using a block to generate complex keys from an object.
```ruby
class SageElements
def initialize
@keys = {
:first => :light,
:light => :forest,
:forest => :fire,
:fire => :water,
:water => :shadow,
:shadow => :spirit,
:spirit => :time,
:time => :first,
}
end
def first_key
@keys[:first]
end
def next_key(pointer)
@keys[pointer]
end
end
sages_hash = sages.to_hash_values(elements.first_key) do |key|
elements.next_key(key)
end
# => {:light=>"Rauru", :forest=>"Saria", :fire=>"Darunia", :water=>"Princess Ruto", :shadow=>"Impa", :spirit=>"Nabooru", :time=>"Zelda"}
```
--------------------------------
### Kernel#class_exists?
Source: https://github.com/battlebrisket/finishing_moves/wiki/Kernel
Checks if a class exists by name.
```APIDOC
## Kernel#class_exists?
### Description
Checks if a class exists and returns a boolean. Requires the class name to be passed as a symbol or string to avoid NameErrors.
### Parameters
- **class_name** (Symbol|String) - Required - The name of the class to check.
### Usage
```ruby
class_exists? :Symbol
# => true
class_exists? :DefinitelyFakeClass
# => false
```
```
--------------------------------
### String#strip_all regex ranges
Source: https://github.com/battlebrisket/finishing_moves/wiki/String
Supports regex character ranges like 0-9, a-z, and A-Z.
```ruby
'0123456789 foo 9876543210'.strip_all('0-9')
# => 'foo'
'FOO 314 BARBAZ'.strip_all('A-Z')
# => '314'
'hello--314--world'.strip_all('a-z')
# => '--314--'
'hello--314--world'.strip_all('a-z-') # note the extra dash at the end
# => '314'
# you can really shoot yourself in the foot if you're not careful
'hello world'.strip_all('a-z')
# => ''
'abcdefghijklm foo123 nopqrstuvwxyz'.strip_all('a-z0-9')
# => ''
```
--------------------------------
### Object#same_as comparison
Source: https://github.com/battlebrisket/finishing_moves/wiki/Object
Normalizes both sides of a comparison into strings before running the equality operator. It works on any class that defines a to_s method.
```ruby
# All these comparisons will return true
:foobar.same_as 'foobar'
'foobar'.same_as :foobar
'1'.same_as 1
2.same_as '2'
3.same_as 3
```
--------------------------------
### Object#is_not_a?
Source: https://github.com/battlebrisket/finishing_moves/wiki/Object
The logical inversion of the is_a? method.
```APIDOC
## Object#is_not_a?
### Description
Returns true if the object is not an instance of the provided class.
### Example
```ruby
[1,2,3].is_not_a? Hash # => true
```
```
--------------------------------
### nil_chain with connected objects
Source: https://github.com/battlebrisket/finishing_moves/wiki/Kernel
Defines classes A, B, and C to demonstrate safe chaining across multiple object associations.
```ruby
class A
attr_accessor :b
def initialize(b)
@b = b
end
end
class B
attr_accessor :c
def initialize(c)
@c = c
end
end
class C
def hello
"Hello, world!"
end
end
c = C.new
b = B.new c
a = A.new b
a.b.c.hello
# => "Hello, world!"
```
--------------------------------
### Kernel#bool_chain usage
Source: https://github.com/battlebrisket/finishing_moves/wiki/Kernel
Demonstrates using bool_chain to return false instead of nil when a method chain breaks.
```ruby
bool_chain{ a.b.c.hello }
# => false
```
--------------------------------
### Numeric#add_percent usage
Source: https://github.com/battlebrisket/finishing_moves/wiki/Numeric
Calculates a percentage of a number and adds it to the original value. Returns a Float.
```ruby
# We need to mark up our widgets by 25% to cover costs
50.add_percent(25)
# => 62.5
1.0.add_percent(10)
# => 11.0
42.add_percent(42)
# => 59.64
12654377184.123123.add_percent(10)
# => 13919814902.535435
```
--------------------------------
### Kernel#bool_chain
Source: https://github.com/battlebrisket/finishing_moves/wiki/Kernel
Executes a block and returns the result, or returns false if the chain breaks.
```APIDOC
## Kernel#bool_chain
### Description
Executes the provided block. If the chain breaks (e.g., due to a nil value), it returns boolean `false` instead of `nil`.
### Usage
```ruby
bool_chain { a.b.c.hello }
# => false
```
```
--------------------------------
### Object#is_one_of?
Source: https://github.com/battlebrisket/finishing_moves/wiki/Object
Checks if the object is an instance of any of the provided classes.
```APIDOC
## Object#is_one_of?
### Description
Performs an `is_a?` check against an array of classes simultaneously.
### Example
```ruby
'a string'.is_one_of? String, Symbol # => true
```
```
--------------------------------
### String#newline_to
Source: https://github.com/battlebrisket/finishing_moves/wiki/String
Normalizes various newline characters (\n, \r, \r\n) into a specified replacement string, defaulting to a single space.
```APIDOC
## String#newline_to
### Description
Converts all newline sequences in a string to a provided replacement string. A bang variant `newline_to!` is available for in-place modification.
### Parameters
- **replacement** (String) - Optional - The string to replace newlines with. Defaults to ' '.
```
--------------------------------
### Object#is_an? usage
Source: https://github.com/battlebrisket/finishing_moves/wiki/Object
An alias for is_a? to improve grammatical flow.
```ruby
1.is_a? Integer
# => true, and a thorn in the side of grammar teachers everywhere!
1.is_an? Integer
# => still true, but now I don't mentally pause every time I read it.
```
--------------------------------
### Handling already formatted or invalid separator UUIDs
Source: https://github.com/battlebrisket/finishing_moves/wiki/String
Shows that correctly formatted UUIDs are returned as-is, while strings with invalid separators like spaces trigger an ArgumentError.
```ruby
"5a658838-7aa4-488c-98f1-21805a5d2021".to_uuid
# => "5a658838-7aa4-488c-98f1-21805a5d2021"
# Only dashes are accepted as separators
"5a658838 7aa4 488c 98f1 21805a5d2021".to_uuid
# => ArgumentError: "5a658838 7aa4 488c 98f1 21805a5d2021" is not a valid UUID
```
--------------------------------
### Object#not_nil?
Source: https://github.com/battlebrisket/finishing_moves/wiki/Object
Returns true if the object is not nil, providing a more readable alternative to !nil?.
```APIDOC
## Object#not_nil?
### Description
Returns true if the object is not nil.
### Example
```ruby
nil.not_nil? # => false
'foobar'.not_nil? # => true
```
```
--------------------------------
### String#replace_whitespace! bang variant
Source: https://github.com/battlebrisket/finishing_moves/wiki/String
Performs whitespace replacement in-place.
```ruby
str = 'a b c d e'
str.replace_whitespace!('-')
str
# => 'a-b-c-d-e'
```
--------------------------------
### Array#to_sym_strict / Array#to_sym_strict!
Source: https://github.com/battlebrisket/finishing_moves/wiki/Array
Converts an array of strings to symbols. The bang variant modifies the array in place.
```APIDOC
## Array#to_sym_strict
### Description
Converts an array of string values into symbols.
## Array#to_sym_strict!
### Description
Modifies the array in place, converting all string elements to symbols.
```
--------------------------------
### String#remove_whitespace
Source: https://github.com/battlebrisket/finishing_moves/wiki/String
Removes all whitespace from a string.
```ruby
' a b c d e'.remove_whitespace
# => 'abcde'
# Absolutely any string is valid
'. $ ^ { [ ( " | " ) * + ?'.remove_whitespace
# => '.$^{[("|")*+?'
```
--------------------------------
### Boolean Checkers (true?, false?, bool?)
Source: https://github.com/battlebrisket/finishing_moves/wiki/Object
Shorthand methods to check if a variable is strictly true, false, or a boolean type.
```APIDOC
## Object#true?, Object#false?, Object#bool?
### Description
Provides boolean checks for TrueClass or FalseClass values.
### Example
```ruby
var.true? # var == true
var.false? # var == false
var.bool? # var == true || var == false
```
```
--------------------------------
### String#nl2br newline conversion
Source: https://github.com/battlebrisket/finishing_moves/wiki/String
Converts various newline formats into HTML break tags.
```ruby
"\n".nl2br
# => "
\n"
"\n\r".nl2br
# => "
\n"
"\r\n".nl2br
# => "
\n"
"\n\r\n".nl2br
# => "
\n
\n"
"\r\n\r\n".nl2br
# => "
\n
\n"
"\r\r\n".nl2br
# => "
\n
\n"
"\r\r".nl2br
# => "
\n
\n"
"\n\r\r".nl2br
# => "
\n
\n"
```
--------------------------------
### Integer#length error handling
Source: https://github.com/battlebrisket/finishing_moves/wiki/Numeric
Demonstrates that calling length on non-integer types like Float raises an ArgumentError.
```ruby
12356469.987.class.name
# => "Float"
12356469.987.length
# => ArgumentError: Cannot get length: "12356469.987" is not an integer
1265437718438866624512.123.class.name
# => "Float" (but it's really BigDecimal)
1265437718438866624512.123.length
# => ArgumentError: Cannot get length: "1.2654377184388666e+21" is not an integer
```
--------------------------------
### String#newline_to with custom delimiter
Source: https://github.com/battlebrisket/finishing_moves/wiki/String
Converts newlines into a specified string, useful for flattening multiline inputs.
```ruby
# imagine a series of ID's coming from a textarea form input
"10001\n10002\n10003\n10004\n10005\n10006".newline_to(',')
# => "10001,10002,10003,10004,10005,10006"
```
--------------------------------
### Kernel#nil_chain
Source: https://github.com/battlebrisket/finishing_moves/wiki/Kernel
Executes a block of code and returns the result, or a specified default value if a NoMethodError or NameError occurs during execution.
```APIDOC
## Kernel#nil_chain
### Description
Executes the provided block. If the execution results in a NoMethodError or NameError (typically due to a nil receiver), it catches the exception and returns the specified return value instead of crashing.
### Signature
`nil_chain(ret_val = nil, &block)`
### Parameters
- **ret_val** (Object) - Optional - The value to return if an exception occurs. Defaults to `nil`.
- **block** (Proc) - Required - The code block containing the method chain to execute.
### Usage Example
```ruby
# Basic usage
nil_chain { foobar.transmogrify }
# With custom return value
nil_chain('N/A') { record.send(field) }
```
```
--------------------------------
### Kernel#silently exception behavior
Source: https://github.com/battlebrisket/finishing_moves/wiki/Kernel
Illustrates that silently does not catch Exception or its descendants, which can lead to program termination.
```ruby
silently{raise Exception}
# => Exception: Exception
silently{raise NoMemoryError}
# => NoMemoryError: NoMemoryError
silently{raise SignalException.new(0)}
# (Closes Ruby)
silently{raise SystemExit}
# (Closes Ruby)
```
--------------------------------
### Object boolean check constraints
Source: https://github.com/battlebrisket/finishing_moves/wiki/Object
Demonstrates that non-boolean types return false for boolean check methods.
```ruby
'true'.bool?
# => false
:true.bool?
# => false
1.true?
# => false
0.false?
# => false
```
--------------------------------
### String#remove_whitespace! bang variant
Source: https://github.com/battlebrisket/finishing_moves/wiki/String
Performs whitespace removal in-place.
```ruby
str = 'a b c d e'
str.remove_whitespace!
str
# => 'abcde'
```
--------------------------------
### String#newline_to! bang variant
Source: https://github.com/battlebrisket/finishing_moves/wiki/String
Performs the newline replacement in-place on the object.
```ruby
txt = "Don't
need
multiple
lines"
txt.newline_to!
txt
# => "Don't need multiple lines"
```
--------------------------------
### Numeric#add_percent
Source: https://github.com/battlebrisket/finishing_moves/wiki/Numeric
Calculates the sum of a numeric value and a specified percentage of that value.
```APIDOC
## Numeric#add_percent
### Description
Calculates the given percentage for a number, adds it to the original number, and returns the sum. Also available as `markup_by_percent`.
### Signature
`Numeric#add_percent(percent)`
### Parameters
- **percent** (Numeric) - The percentage value to add.
### Returns
- **Float** - The resulting value after addition.
```
--------------------------------
### String#dedupe multiple characters
Source: https://github.com/battlebrisket/finishing_moves/wiki/String
Deduplicate multiple characters by passing them as a single string.
```ruby
'foo___bar_baz---bing'.dedupe('-_')
# => 'foo_bar_baz-bing'
```
--------------------------------
### Hash#delete_each usage
Source: https://github.com/battlebrisket/finishing_moves/wiki/Hash
Deletes multiple keys from a hash and returns a hash containing the deleted entries. Keys not found in the hash are ignored.
```ruby
mega_man_bosses = { :metal_man => 1, :bubble_man => 2, :heat_man => 3, :wood_man => 4 }
mega_man_bosses.delete_each :chill_penguin, :spark_mandrill
# => nil, and get your series straight
mega_man_bosses
# => { :metal_man => 1, :bubble_man => 2, :heat_man => 3, :wood_man => 4 }
mega_man_bosses.delete_each :metal_man
# => { :metal_man => 1 }
mega_man_bosses
# => { :bubble_man => 2, :heat_man => 3, :wood_man => 4 }
mega_man_bosses.delete_each :bubble_man, :heat_man, :wheel_gator
# => { :bubble_man => 2, :heat_man => 3 }
mega_man_bosses
# => { :wood_man => 4 }
```
--------------------------------
### Object#is_one_of? usage
Source: https://github.com/battlebrisket/finishing_moves/wiki/Object
Checks if an object is an instance of any class provided in the argument list.
```ruby
a = 'a string'
a.is_one_of? String, Symbol, OpenSSL, PrettyPrint
# => true
b = :a_symbol
b.is_one_of? String, Symbol, OpenSSL, PrettyPrint
# => true
c = ['an array']
c.is_one_of? String, Symbol, OpenSSL, PrettyPrint
# => false
```
--------------------------------
### Fixnum#to_bool integer conversion
Source: https://github.com/battlebrisket/finishing_moves/wiki/Boolean-Typecasting
Converts 0 to false and 1 to true. Any other integer value raises an ArgumentError.
```ruby
0.to_bool
# => false
1.to_bool
# => true
2.to_bool
# => ArgumentError: invalid value for Boolean: "2"
-1.to_bool
# => ArgumentError: invalid value for Boolean: "-1"
8675309.to_bool
# => ArgumentError: invalid value for Boolean: "8675309"
```
--------------------------------
### Strict Boolean Checkers (true_?, false_?)
Source: https://github.com/battlebrisket/finishing_moves/wiki/Object
Strict boolean checks that raise a RuntimeError if the value is not a boolean.
```APIDOC
## Object#true_?, Object#false_?
### Description
Checks if the value is a boolean, raising a RuntimeError if it is not.
### Example
```ruby
true.true_? # => true
nil.false_? # => RuntimeError
```
```
--------------------------------
### String#to_uuid
Source: https://github.com/battlebrisket/finishing_moves/wiki/String
Formats a 32-character hexadecimal string into a standard UUID string. Throws an ArgumentError if the input is not exactly 32 hexadecimal characters or contains invalid characters.
```APIDOC
## String#to_uuid
### Description
Formats a string containing a UUID without dashes into the standard UUID display format (e.g., 8-4-4-4-12).
### Signature
`String#to_uuid`
### Requirements
- Input must contain only hexadecimal characters (0-9, A-F).
- Input must be exactly 32 characters in length.
### Errors
- `ArgumentError`: Raised if the string contains non-hexadecimal characters, is not 32 characters long, or uses invalid separators.
### Example
```ruby
"cab93178ba44438c85b149fed89e8a6f".to_uuid
# => "cab93178-ba44-438c-85b1-49fed89e8a6f"
```
```
--------------------------------
### Object#is_an?
Source: https://github.com/battlebrisket/finishing_moves/wiki/Object
An alias for the standard Ruby is_a? method for improved readability.
```APIDOC
## Object#is_an?
### Description
Alias for `is_a?`.
### Example
```ruby
1.is_an? Integer # => true
```
```