defined?
expression tests whether or not expression refers to anything recognizable (literal object, local variable that has been initialized, method name visible from the current scope, etc.). The return value isnil
if the expression cannot be resolved. Otherwise, the return value provides information about the expression.
Let me explain with an example :-
defined?("a") # => "expression"
# this returns "method", as there is a method defined on the class String. So, the
# method invocation is possible, and this is a method call, thus returning `"method"`.
defined?("a".ord) # => "method"
# it return nil as there is no method `foo` defined on `"a"`,
# so the call is not possible.
defined?("a".foo) # => nil
Now coming to your point :-
As you said data[0]
gives a Fixnum
instance, and of-course Fixnum#[]
exist. Thus fixnum_instance[:some_param]
is also a valid method call. It just testing if the method is defined or not. If defined, it will tell yes this is a "method"
expression. Otherwise nil
. Not actually will check if the method call succeeded or not.
In Ruby all objects has truthy values except nil
and false
, thus "method"
being a string object also has the truthy value, thus your condition got succeeded.