How do I write a function in rails console that takes in an array of characters?

541 Views Asked by At

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?

4

There are 4 best solutions below

0
On BEST ANSWER

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:

def doSomething(value)
  if (value.is_a?(Array))
    value.any_array_method # For eg: value.include?('a')
  else
    raise "Expected array value"
  end
end

And you can call it like:

doSomething(['a', 'b', 'c'])

and if you call it with any other argument than array then it will give:

RuntimeError: Expected array value

You can pass an error message too instead of raising an exception that depends on you.

Hope this helps.

0
On

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.

0
On

Please try this.

#here argument name can be anything. It not compulsory to use array as argument name, it can be anything like `string`, `xyz` etc 

def function(array)
  p array
end

function([1,2,3,4,5])
0
On

You can do it by doing

def my_function(arr=[], s)
  puts arr.inspect
  puts s.inspect
end

you can call the method with

my_function([1,3,4], "string")