gotchas and stack traces in ruby
TRANSCRIPT
Gotchas and Stack Traces in
RubyOmbuLabs, September 2015
#1: Whitespacedef method(arg1, arg2)end
method 1, 2 # OKmethod(1, 2) # OKmethod (1, 2) # Error!
SyntaxError: (irb):24: syntax error, unexpected ',', expecting ‘)'from (irb):7:in `method'
#1: Whitespacedef method 42end
num = 21method/num # OKmethod / num # OKmethod/ num # OKmethod /num # Error!
ArgumentError: wrong number of arguments (1 for 0)
from (irb):7:in `method'
#2: True & False[].any? => false[1].any? => true[:foo, :bar].any => true
[false].any? => false[nil].any? => false[false, nil].any? => false[false, true].any? => true
`any?` is actually “Are any elements truthy?”
#3: Constants (not)FOO = 5 => 5 FOO = 7(irb):3: warning: already initialized constant FOO => 7 FOO => 7
Constants can be reassigned, Ruby will just throw a warning and let you do it anyway.
def foo 0/0end
def bar fooend
def baz barend
baz
➜ ombushop git:(develop) ✗ ruby test.rbtest.rb:2:in `/': divided by 0 (ZeroDivisionError)
from test.rb:2:in `foo'from test.rb:6:in `bar'from test.rb:10:in `baz'from test.rb:13:in `<main>'
def foo my_correctly_spelled_variable = "hey!" puts my_incorrectly_spelled_variableend
def bar fooend
def baz barend
baz
➜ ombushop git:(develop) ✗ ruby test.rbtest.rb:3:in `foo': undefined local variable or method `my_incorrectly_spelled_variable' for main:Object (NameError)
from test.rb:7:in `bar'from test.rb:11:in `baz'from test.rb:14:in `<main>'
def foo my_correctly_spelled_variable = "hey!" puts my_incorrectly_spelled_variableend
def bar my_incorrectly_spelled_variable = "hey!" fooend
def baz my_incorrectly_spelled_variable = "hey!" barend
baz
undefined local variable or method `my_incorrectly_spelled_variable' for main:Object (NameError)
➜ ombushop git:(master) ✗ ruby test.rbtest.rb:3:in `foo': undefined local variable or method `my_incorrectly_spelled_variable' for main:Object (NameError)
from test.rb:8:in `bar'from test.rb:13:in `baz'from test.rb:16:in `<main>'
TL;DR: Always paste the full stack trace of the error you come across when asking for help.
THANK YOU!questions?