I know when writing a function that takes a string, it looks like:
def function("string")
but how do I write one that takes an array? should I first define an empty array e.g. s=[] and then when writing the function, just use s as the input?
I know when writing a function that takes a string, it looks like:
def function("string")
but how do I write one that takes an array? should I first define an empty array e.g. s=[] and then when writing the function, just use s as the input?
This is really a question about Ruby than Rails. Ruby is a dynamic typing language, which in method definition, means you don't declare the argument types:
def add_three ( x, y , z)
x + y + z
end
add_three(1, 2, 3) # 6
add_three('a', 'b', 'c') # 'abc'
add_three([2], [3], [4], # [2, 3, 4]
add_three(Date.new(2017,3,4), 1, 1), # new date 2017.3.6
What matters is that x has a method +
that accepts y, and the result from x + y
has a method +
that accepts z. This is called duck typing. What's important here is not which class the object is, but what message it can respond to.
As Ruby is dynamic language and it supports Duck Typing we never declare the data type of the variables or arguments of the method. So you could pass the array in any method, ruby just cares about the methods you can use on that argument which is an object for it. So to be sure about the array methods you are using will execute on array only you can do like this:
And you can call it like:
and if you call it with any other argument than array then it will give:
You can pass an error message too instead of raising an exception that depends on you.
Hope this helps.