Ruby use case for nil, equivalent to Python None or JavaScript undefined -
how ruby's nil
manifest in code? example, in python might use none default argument when refers argument, in ruby can refer other arguments in arg list (see this question). in js, undefined
pops more because can't specify default arguments @ all. can give example of how rubynone
pops , how it's dealt with?
i'm not looking example using nil
. preferably real code snippet had use nil
reason or other.
ruby's nil , python's none
pretty equivalent (they represent absence of value), people coming python may find surprising behaviors. first, ruby returns nil
in situations python raises exception:
accessing arrays , hashes:
[1, 2, 3][999] # nil. [].fetch(0) raises indexerror {"a" => 1, "b" => 2}["nonexistent"] # nil. {}.fetch("nonexistent") raises indexerror
instance instance variables:
class myclass def hello @thisdoesnotexist end end myclass.new.hello #=> nil
the second remarkable fact nil
object lots of methods, can convert integer, float or string:
nil.to_i # 0 nil.to_f # 0.0 # integer(nil) or float(nil) raise typeerror. nil.to_s # ""
unsurprisingly, python programmers tend dislike permissive behaviour (i did @ first), it's ok once used it.
i not sure answers question, 2 cents.
Comments
Post a Comment