What is the preferred way (best style) for defining a single line method in Ruby?

What is the best style:

def method; some code end 

or

 def method() some code end 

and why?

+4
source share
3 answers

The preferred way is not to define the method on one line, as @Romain said.

 def method some code end 
+9
source

Some people use {} instead of begin; end begin; end when writing blocks on only one line.

Perhaps this suits your needs:

 class A define_method(:method_name) { |arg1, arg2| do_something } end 
+2
source

The definition of a method on one line should be done only in the documentation, otherwise divide it into three lines:

 def method some code end 

If you find that you have many methods with one liner (i.e. getters and setters), there can be many metaprogramming methods to reduce duplication (for example, using define_method ). For example, you can use :attr_accessor to define many getters and setters:

 class Person # defines name, name=, age, age=, ... attr_accessor :name, :age, :blood_type end 

Here is a ruby ​​forum that talks about it. I also highly recommend reading Ruby Metaprogramming . It has many goodies, like 3 or 4 ways to solve your problem, as well as many other methods to reduce duplication.

0
source

Source: https://habr.com/ru/post/1383076/


All Articles