single-line method in ruby

To write a single-line method in Ruby, you can use the -> (lambda) syntax or the def syntax without using curly braces or the end keyword.

Here's an example using the -> (lambda) syntax:

main.rb
# Using the -> syntax
method_name = ->(param1, param2) { param1 + param2 }
75 chars
3 lines

And here's an example using the def syntax:

main.rb
# Using the def syntax
def method_name(param1, param2) param1 + param2 end
75 chars
3 lines

Both syntaxes achieve the same result of creating a single-line method. However, it's important to note that single-line methods are typically best suited for small and simple methods. For more complex methods, it's generally recommended to use multi-line syntax for better readability.

Keep in mind that although Ruby allows single-line methods, it's still a good practice to separate statements onto multiple lines for readability and maintainability purposes in most cases.

If you need to do more complex operations within the method, it's advisable to use multi-line syntax.

related categories

gistlibby LogSnag