Class: String

Inherits:
Object show all
Defined in:
lib/patch/let.rb,
lib/patch/foobar.rb

Overview

Extends the String class with methods for system execution and output.

Instance Method Summary collapse

Instance Method Details

#echoObject

Prints the string to the console, followed by a newline.



237
238
239
# File 'lib/patch/foobar.rb', line 237

def echo
  tap { puts self }
end

#exec(args = {}) ⇒ Boolean?

Executes the string as a system command. Allows for substituting arguments into the string using sprintf format.

Examples:

"ls -l %{dir}".exec(dir: "/tmp")
"echo 'Hello World'".exec # => true (prints "Hello World")
"ruby -e 'exit 1'".exec # => false

Parameters:

  • args (Hash) (defaults to: {})

    A hash of arguments to be interpolated into the command string. The keys are used in sprintf-style formatting (e.g., ‘%key`).

Returns:

  • (Boolean, nil)

    Returns true if the command was found and ran successfully (exit status 0), false if the command returned a non-zero exit status, and nil if command execution failed (e.g., command not found).



232
233
234
# File 'lib/patch/foobar.rb', line 232

def exec(args = {})
  system(self % args)
end

#valid_name?(target = :method) ⇒ Boolean

Checks if the string is a valid Ruby method or variable name.

Valid method names can include letters, numbers, underscores, and may end with ‘!`, `=`, or `?`. Valid variable names can include letters, numbers, and underscores but cannot end with `!`, `=`, or `?`.

Examples:

"my_method".valid_name?                # => true
"my_method?".valid_name?               # => true
"setter=".valid_name?                 # => true
"_private_method!".valid_name?         # => true
"ConstantLike".valid_name?             # => true
"1invalid".valid_name?                 # => false (starts with a number)
"invalid-name".valid_name?             # => false (contains hyphen)

"my_variable".valid_name?(:variable) # => true
"_var".valid_name?(:variable)        # => true
"my_variable?".valid_name?(:variable)# => false (ends with ?)
"A_CONSTANT".valid_name?(:variable)  # => true

Parameters:

  • target ([:method, :variable, :var]) (defaults to: :method)

    Whether to validate as a method name or a variable name. Defaults to :method.

Returns:

  • (Boolean)

    true if the string is a valid name for the specified target, false otherwise.



72
73
74
75
76
77
78
79
80
81
# File 'lib/patch/let.rb', line 72

def valid_name?(target = :method)
  case target
  when :method
    self =~ /\A[a-zA-Z_]\w*[!?=]?\z/
  when :var, :variable
    self =~ /\A[a-zA-Z_]\w*\z/
  else
    false
  end
end