Blog

Thoughts from my daily grind

Intro to Endless Functions in Ruby

Posted by Ziyan Junaideen |Published: 19 November 2022 |Category: Ruby Language
Default Upload |

Ruby is a language that prioritises developer happiness. This raises the question, how does one make a developer happy? As with any child, you feed a developer sweets to keep them happy.

Ruby 3 introduces "Endless Functions" to keep developers excited. This is considered experimental, I love it and this is what it looks like:

def name(args) = expression

If you are like me, you might prefer some examples, so let me.

Examples

If you don't have any arguments to pass, you do not need parenthesis. If you do, parenthesis is required.

# No arguments => parenthesis not required!
class UserSerializer < ActiveModel::Serializer
  # ...

  def created_at = object.created_at&.iso8601
end

# Has arguments => parenthesis required
module ApplicationHelper
  def format_time(time) = time&.strftime(TIME_FORMAT)
end

You are not restricted to one line. You can go multiple lines, depending on your case.

def request_params = {
  headers: request_headers,
  body: request_body
}

def request_headers = {
  'Content-Type' => 'application/json',
  'X-Idempotency-Key' => idempotency_key,
  'X-Wait-For' => 'real-response'
}

I also like to use them to obtain comparison and operand results:

def adult?(age) = age >= 18

def call
  return unless adult?
  # ...
end

# However I prefer it not to escalate beyond
# (example from the Ruby style guide)
def fib(x) = if x < 2
  x
else
  fib(x - 1) + fib(x - 2)
end

You can also use it to define a method in a Ruby object, I don't remember when I last had to do it though 🤔

user = User.find(...)
def user.full_name = "#{first_name} #{last_name}"

Conclusion

The point of good code is not to execute on a computer, but for another developer (including yourself in the future) to easily follow, understand and maintain. Ruby does a great job in this department.

While "experimental", Endless Methods is in-my-opinion a great addition to the language. It helps us write clean code and that is all that matter to me.

I love it! What do you think about it?

About the Author

Ziyan Junaideen -

Ziyan is an expert Ruby on Rails web developer with 8 years of experience specializing in SaaS applications. He spends his free time he writes blogs, drawing on his iPad, shoots photos.

Comments