By Ronak Gothi
Ruby provides several ways using which one can write one line functions. However, over the years, having done several code reviews, I've seen this feature seldom used. In this article, we will go through various way of writing single-line functions.
One line functions as the name imply is a short function which takes 1 LOC. Because they are short and crisp they are easier to read, maintain and follows the single responsibility principle well.
Syntax
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
def hello; puts "hi"; end;
hello # hi
def hello puts "hi"; end;
hello # syntax error, unexpected `end', expecting end-of-input
def hello(); puts "hi"; end;
hello # hi
def hello() puts "hi"; end;
hello # hi
def hello() puts "hi" end
hello # hi
def multiply a, b; puts a * b end
multiply(2, 2) # 4
def multiply(a, b) puts a * b end
multiply(2, 2) # 4
def multiply(a, b) puts a * b; end;
multiply(2, 2) # 4
One could use metaprogramming concepts from ruby to write oneline functions. Metaprogramming introduces a lot of magic and should be used with greater responsibility.
1
2
3
4
5
define_method(:add) { |*params| puts params.inject(:+) }
add(1, 2, 3, 4) # 10
define_method(:greet) { |a, b| puts "Hello #{a} & #{b}" }
greet('Mark', 'Price') # Hello Mark & Price
Ruby 3.0 introduces endless function. This allows programmers to write oneline functions which closely resembles functions in javascript world.
Syntax: def: value(args) = expression
Rewriting the above example into endless function.
1
2
3
4
5
def hello() = puts "hi"
hello # hi
def multiply(a, b) = puts a * b
multiply(2, 2) # 4