I am a beginner in Ruby and I am having trouble with if else statement. As you know, Ruby will return the last calculated code if the return keyword is not specified.
Here is the issue.
def aMethod(*args)
if args[-1].class == String
if args.length > 1
args[-1]
elsif args.length == 1
args[-1][-1]
end
end
end
The above code snippet will run correctly if I run the method with Strings as input.
p aMethod("String1", "String2") => #return "String 2"
p aMethod("String1") => return "1"
If I add another if block as shown below
def aMethod(*args)
if args[-1].class == String
if args.length > 1
args[-1]
elsif args.length == 1
args[-1][-1]
end
end
# adding another if block
if args[-1].class == Integer
args[-1]
end
#
end
Using the same input will cause the program to return nil for both methods that accept String as an input as shown below
p aMethod("String1", "String2") => #return nil
p aMethod("String1") => # return nil
p aMethod(1,2,3,4) => # return 4
Why is this so?