Module: FStrings

Extended by:
FStrings
Included in:
FStrings
Defined in:
lib/fstrings.rb,
lib/fstrings/parser.rb,
lib/fstrings/formats.rb

Overview

Python-alike fstrings (formatting strings) with a Ruby flavour.

Examples:

include FStrings

i = 1
f = 1.23

# Basic form: Just like #{}
f"Simple! {i}"
# => "Simple! 1"

# Inline formatting is supported, same flags as Kernel#format
f"Look: {i%+i}"
# => "Look: +1"
f"Floats... {f%.1f}"
# => "Floats... 1.2"

# Any statement is supported:
f"The whole statement: {i + f %.1f}"
# => "The whole statement: 2.2"

# = at the end of statement handy for debugging:
f"Variable names, too! {i + f = %.1f}"
# => "Variable names, too! i + f = 2.2"

# Time and date formatting is supported:
f"Currently, it is {Time.now %H:%M (at %b %d)}"
# => "Currently, it is 14:31 (at Jan 07)"

# Custom object formatting definition is supported:
Point = Struct.new(:x, :y)
FStrings.def_formatter(Point) { |val, fmtstring| fmtstring % [val.x, val.y] }
f"The point: [{p= %.1f;%.1f}]"
# => "The point: [p= 1.3;2.5]"

Defined Under Namespace

Modules: Formats, Parser

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.def_formatter(klass) { ... } ⇒ Object

Define custom formatters for user classes. Formatting block should accept ‘value` of specified class, and formatting `string`, and return string.

See main FStrings docs for a (simplistic) example of usage.

Yields:

  • value Of the specified ‘klass`

Yield Returns:

  • String



66
67
68
# File 'lib/fstrings.rb', line 66

def self.def_formatter(klass, &formatter)
  Formats[klass] = formatter
end

Instance Method Details

#f(string) ⇒ Object

Main library’s interface. See FStrings main docs for examples.



49
50
51
52
# File 'lib/fstrings.rb', line 49

def f(string)
  # TODO: cache str2code results?
  binding.of_caller(1).eval(Parser.str2code(string))
end