ConstantLearning
ConstantLearning

Reputation: 43

Returning arrays from methods in Ruby

How does one return an array from a Ruby method?

Example:

def array(a,b,c)
  WHAT DO I TYPE NOW TO RETURN ["a","b","c"]
end

P.S: I am new to this so I apologize in advance in anything in my question seems stupid to anyone.

Upvotes: 2

Views: 1070

Answers (3)

Boris Stitnicky
Boris Stitnicky

Reputation: 12578

Return arity can get important at times, your question was well justified. In Ruby, method return arity is formally always 1, that is, only 1 object is returned. But we can de facto achieve higher arity by returning a collection type. You can do it like this:

def hello
  [ "hello", "world" ]
end

Returning arrays has also special syntactic support:

def hello2
  return "hello", "world"
end

Try it and see that it works:

hello #=> [ "hello", "world" ]
hello2 #=> [ "hello", "world" ]
a, b = hello
a #=> "hello"
b #=> "world"

Upvotes: 2

pangpang
pangpang

Reputation: 8821

The value of the last expression is the default return value of a method in ruby.

I don't know why you want to return an array, but you can make it like this.

def test
    ["a", "b", "c"]
end

2.1.2 :070 > test
=> ["a", "b", "c"]

def test(a, b, c)
    [a, b, c]
end

2.1.2 :076 > test("a", "b", "c")
 => ["a", "b", "c"]

Upvotes: 0

Chuck
Chuck

Reputation: 237010

The same way you return anything else. If you want a method that returns the number 1, you'd write:

def one
  1
end

Here, instead of the number 1, you want to return an array. But there is nothing special about arrays — just like you put the number 1 as the last expression in the method, you put an array there.

Upvotes: 0

Related Questions