user15672038
user15672038

Reputation:

implicit return with variable assignment

according to the most popular style guides:

# this a bad
def some_function
  return "some value"
end

# this is good
def some_function
  "some value"
end

I'm working with Ruby on Rails and I often see code like this, which those style guides don't mention:

def some_function(x)
  result = some_calculations(x)
  result
end

I've tried this and it works, so I don't understand the rationale of explicitly returning the variable after the assignment in the next line:

# this works as well
def some_function(x)
  result = some_calculations(x)
end

Upvotes: 1

Views: 590

Answers (1)

max
max

Reputation: 101976

There is actually no rationale in assigning the local variable at all since it goes out of scope immediately. So the "correct way" to write the method is actually:

def some_function(x)
  some_calculations(x)
end

Even if you do what to do some operations with the result you can use then and tap instead of assigning a local variable:

def some_function(x)
  some_calculations(x).then do |value|
    value ** 2
  end
end

Upvotes: 1

Related Questions