Reputation: 13378
Using Rails 3. Here's a sample method:
def all_users
users.as_json
end
Must we always have a return
in a method? The above works, but is th
def all_users
u = users.as_json
u
end
Another thing, I tried to apply returning
, but it must always be enclosed with do ... end
?
Any better way to write methods?
Upvotes: 1
Views: 60
Reputation: 1138
In Ruby, the last executed (thanks mharper) line of a method is returned.
So this:
def all_users
users.as_json
end
This:
def all_users
u = users.as_json
u
end
And this:
def all_users
u = users.as_json
return u
end
Do the same thing.
Upvotes: 1
Reputation: 19031
Rubyists prefer omitting return
keyword when they can. So in your case, this is the preferred way to write the method
def all_users
users.as_json
end
And to your second question
I tried to apply returning, but it must always be enclosed with do ... end?
do
and end
are as a combination are used to write something called "blocks" in Ruby. Practically speaking, blocks are special kind of iterative methods that work on arrays, hashes, enumerable etc. You don't have to enclose return
keyword within do
and end
.
Upvotes: 1