mirror of
https://github.com/jbranchaud/til
synced 2026-07-02 23:58:25 +00:00
Add Load A Module And Execute A Statement as a Ruby TIL
This commit is contained in:
@@ -10,7 +10,7 @@ working across different projects via [VisualMode](https://www.visualmode.dev/).
|
||||
|
||||
For a steady stream of TILs, [sign up for my newsletter](https://visualmode.kit.com/newsletter).
|
||||
|
||||
_1755 TILs and counting..._
|
||||
_1756 TILs and counting..._
|
||||
|
||||
See some of the other learning resources I work on:
|
||||
|
||||
@@ -1451,6 +1451,7 @@ If you've learned something here, support my efforts writing daily TILs by
|
||||
- [Limit Split](ruby/limit-split.md)
|
||||
- [List The Running Ruby Version](ruby/list-the-running-ruby-version.md)
|
||||
- [Listing Local Variables](ruby/listing-local-variables.md)
|
||||
- [Load A Module And Execute A Statement](ruby/load-a-module-and-execute-a-statement.md)
|
||||
- [Make A Long String Of Text Readable](ruby/make-a-long-string-of-text-readable.md)
|
||||
- [Make An Executable Ruby Script](ruby/make-an-executable-ruby-script.md)
|
||||
- [Make Structs Easier To Use With Keyword Initialization](ruby/make-structs-easier-to-use-with-keyword-initialization.md)
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
# Load A Module And Execute A Statement
|
||||
|
||||
Here is a nice one-liner pattern for use with the `ruby` executable.
|
||||
|
||||
```bash
|
||||
$ ruby -r file.rb -e 'MyClass.do_something'
|
||||
```
|
||||
|
||||
The `-r` flag loads (requires, really) a Ruby file at the specified path. The
|
||||
`-e` flag will execute the line of Ruby code that you give it, in that context.
|
||||
In combination that means I can load some module into the execution environment
|
||||
and then I can run some code that uses that module.
|
||||
|
||||
A more practical example of that is how I demonstrated the behavior of a
|
||||
`MarkdownHelpers` module in [Create A Module Of Utility
|
||||
Functions](create-a-module-of-utility-functions.md).
|
||||
|
||||
```bash
|
||||
$ ruby -r ./markdown_helpers.rb -e 'puts MarkdownHelpers.link("Click here", "https://example.com")'
|
||||
[Click here](https://example.com)
|
||||
```
|
||||
|
||||
The `MarkdownHelpers` module that I've defined in `./markdown_helpers.rb` is
|
||||
loaded into context and I can now access and execute that module to try out
|
||||
parts of it. All in a single line in the terminal.
|
||||
Reference in New Issue
Block a user