Chautauqua Logo

Ruby module Kernel (summary) interactive

Show iconIcon Show more Hide iconIcon Hide more
Prompt icon → Click to get an interactive sample (type in code)

Methods

Converting

Array()Array([1,2,3]) # [1,2,3] Documentation Interactive samplePlayground
[1, 2, 3]
Float()Float(1); Float('1') # 1.0 Documentation Interactive samplePlayground
1.0
Hash()Hash({a:1,b:2}); Hash(nil) # {a:1,b:2}; {} Documentation Interactive samplePlayground
{a: 1, b: 2}
Integer()Integer(1); Integer('1') # 1 Documentation Interactive samplePlayground
1
Integer()Integer("08"); Integer("08",10) # Error; 8
String()String('a'); String('1') # 'a'; '1' Documentation Interactive samplePlayground
"1"
Array('s') => ["s"]
's'.to_a → undefined method 'to_a' for instance of String (NoMethodError)

Querying

class[1,2,3].class # Array Documentation Interactive samplePlayground
Array
block_given?def m;if block_given?;yield;else;'✗';end;end Documentation Interactive samplePlayground
✗; yes
frozen?t='ice'; t.freeze; t.frozen? # true Documentation Interactive samplePlayground
true

Exiting

exit(status=true)exit # Runs 'at_exit' hooks Documentation
exit!(status=false)exit! # Does not run 'at_exit' hooks Documentation
at_exitat_exit { puts 'at_exit function.' } Documentation
abort(msg)abort('Stop this') # Stop this Documentation

Exceptions

raise (alias fail)begin; raise(StandardError,'✗'); Documentation
rescue => x; p x.message; end # '✗' Documentation
catch (none raise)catch(1) { '✗' } # '✗' Documentation
throw (none raise)catch(:obj_A) { throw(:obj_A, '✗') } # '✗' Documentation
          # rescue => e is syntax that assigns $! to a nicer variable name
          begin
  raise ArgumentError, 'bad input'
rescue => e
  puts e              # bad input
  puts $!             # bad input
  puts e.equal?($!)   # true
end

IO

putsputs 'text' # Adds new line Documentation
printprint 'text' # No new line Documentation
pp 'text' # Inpects with new line Documentation
pppp({n:'Bo',l:['Ruby','JS',…]}) # Add new lines Documentation
printfprintf('%4.4d %4s',24,24,24.0) # 0024 24=> nil Documentation
getsname = gets.chomp (.chomp → Remove \n) # Name Documentation

Procs

lambdasq = lambda {|x| x*x}; sq = ->(x) {x*x} # 25 Documentation
procs=Proc.new{|x|x*x}; s.call(5); s.(5); s[5] # 25 Documentation
          # A lambda enforces the exact number of arguments
          # A proc just fills in nil for missing ones and ignores extras
          strict = ->(a, b) { puts "#{a}, #{b}" }
strict.call(1)        # ArgumentError: wrong number of arguments
                        (given 1, expected 2)

loose = proc { |a, b| puts "#{a}, #{b}" }
loose.call(1)         # "1, " (b is nil, no error)
loose.call(1, 2, 3)   # "1, 2" (3 is silently dropped)
          # RETURN BEHAVIOR
# Inside a lambda, return just exits the lambda and hands control back to whoever called it — like a normal method.
def test_lambda
  l = -> { return 10 }
  l.call
  puts 'still running' # this DOES print
  20
end

puts test_lambda # prints "still running", then 20

# Inside a proc, return tries to return from the enclosing method — it doesn't just exit the proc.
def test_proc
  p = proc { return 10 }
  p.call
  puts 'still running' # this is NEVER reached
  20
end

puts test_proc # prints 10 (never gets to "still running" or 20)
          # The dangerous case the exam likes: if you call that same proc outside the method it was defined in (e.g., return it and call it later), you get a LocalJumpError because there's no enclosing method left to return from.
          def make_proc
  proc { return 5 }
end

p = make_proc
p.call   # LocalJumpError: unexpected return

Tracing

Subprocesses

Loading

requirerequire 'cgi'; require 'cgi' # true;false Documentation
require_relativerequire_relative 'lib/chau'; req… # true;false Documentation
loadload 't/tasks.rb' # true Documentation
autoloadautoload(:MyM,'m/my') (load on first use) # nil Documentation

Yielding

tap(1..3).tap{|x|p x}.to_a.tap{|x|p x}.map{|x|x*x}.tap{|x|p x} # 1..3;[1,2,3];[1,4,9] Documentation
then (alias yield_self)3.next.then {|x| x**x } # 256 Documentation

Random Values

randrand;rand(-0.5);rand(10);rand(-10); # 0.53…;7 Documentation
srandsrand(3);rand(9);rand(9);srand(3);rand(9);rand(9) # 3022…;7,5;3;7,5 Documentation

Other

evals="Hello";eval("s+' World'") # Hello World Documentation
loopn=0;loop do;n+=1;p n;break if n==3;end # 1,2,3 Documentation
sleepsleep(3) # ⏱ Documentation
format (alias sprintf)format('%05d', 42) # 00042 Documentation
warnwarn("msg 1", "msg 2") # msg 1; msg 2 Documentation