Module: Kernel

Defined in:
lib/shenanigans/kernel/fn.rb,
lib/shenanigans/kernel/with.rb,
lib/shenanigans/kernel/prompt.rb,
lib/shenanigans/kernel/require_optional.rb

Constant Summary collapse

CONVERSIONS =

Currently only used by prompt: :to_i, :to_f, :to_r, :to_sym, :to_c

[:to_i, :to_f, :to_r, :to_sym, :to_c]

Instance Method Summary collapse

Instance Method Details

#fn(*funs) ⇒ Object

Composes a list of functions. Functions can be specified as symbols or lambdas.

Examples:

Composing symbols

["foo bar", "baz qux"].map(&fn(:split, :last)) #=> ["bar", "qux"]

Composing symbols and lambdas

(1..3).map(&fn(:next, -> x { x * x }, -> x { x.to_f / 2 } ))
#=> [2.0, 4.5, 8.0]


10
11
12
13
14
15
16
# File 'lib/shenanigans/kernel/fn.rb', line 10

def fn(*funs)
  ->(x) do
    funs.inject(x) do |v, f|
      Proc === f ? f.call(v) : v.send(f)
    end
  end
end

#prompt(text = "", conversion = nil) ⇒ Object

Displays a prompt and returns chomped input. Modelled after the Python method raw_input, but also can be supplied with an optional conversion method.

Examples:

A simple prompt

prompt("Prompt> ")
Prompt> 12 #=> "12"

A prompt with conversion

prompt("Prompt> ", :to_f)
Prompt> 12 #=> 12.0


16
17
18
19
20
# File 'lib/shenanigans/kernel/prompt.rb', line 16

def prompt(text = "", conversion = nil)
  print text unless text.empty?
  input = gets.chomp
  CONVERSIONS.include?(conversion) ? input.send(conversion) : input
end

#require_optional(gem, &block) ⇒ Object

Optionally require a gem. If it is not available, nil will be returned. Alternatively, a block can be provided with code to run.

Examples:

Without a block

require "non_existent" #=> nil

With a custom block

require "non_existent" do
  puts "Something went wrong"
end #=> Outputs "Something went wrong"


12
13
14
15
16
# File 'lib/shenanigans/kernel/require_optional.rb', line 12

def require_optional(gem, &block)
  require gem
rescue LoadError
  block&.call
end

#with(o, &blk) ⇒ Object

A Pascal/ActionScript like with method. Yields its argument to the provided block and then returns it.

Examples:

with([]) do |a|
  a << "a"
  a << "b"
end #=> ["a", "b"]


10
11
12
# File 'lib/shenanigans/kernel/with.rb', line 10

def with(o, &blk)
  o.tap(&blk)
end