Reputation: 971
Could someone give me an example of a method that accepts a single string argument. Whilst i appreciate this might seem trivial I am trying to understand how this works in ruby. Would the syntax below be correct.
Def method("argument")
true
end
Upvotes: 0
Views: 2687
Reputation: 59262
You need to check if it is a string by yourself. You can make use of is_a?
to see if it is a String
as Ruby is dynamically typed.
def add_watson(f_name)
f_name << " Watson" if f_name.is_a? String
end
Now, calling it
puts add_watson("Emma") #=> Emma Watson
Upvotes: 1
Reputation: 4485
Your syntax is wrong.
def method(arg)
puts "arg"
end
You can review some tutorial too
http://www.tutorialspoint.com/ruby/ruby_methods.htm
http://www.skorks.com/2009/08/method-arguments-in-ruby/
Upvotes: -1
Reputation: 51171
No, it wouldn't. First of all, def
keyword is lowercased. Also, method argument(s) is written like this def my_method(argument)
and at this point it doesn't check if it's string, in fact, it can accept any object, because Ruby is typed dynamically. If you want to force String
instance as an argument, you can do it inside of method body:
def my_method(argument)
raise ArgumentError, "argument must be a String" unless argument.is_a? String
true
end
Upvotes: 1