Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I define a method on one line in Ruby?

Tags:

ruby

Is def greet; puts "hello"; end the only way to define a method on one line in Ruby?

like image 427
RyanScottLewis Avatar asked Nov 29 '10 07:11

RyanScottLewis


People also ask

How do you define a method in Ruby?

Defining & Calling the method: In Ruby, the method defines with the help of def keyword followed by method_name and end with end keyword. A method must be defined before calling and the name of the method should be in lowercase. Methods are simply called by its name.

How do you reference a method in Ruby?

You can get a reference to the method by object. method(:method_name) . Eg: To get a reference to system method.

What is Def and end in Ruby?

The code def hi starts the definition of the method. It tells Ruby that we're defining a method, that its name is hi . The next line is the body of the method, the same line we saw earlier: puts "Hello World" . Finally, the last line end tells Ruby we're done defining the method.

Do you need a main method in Ruby?

@Hauleth's answer is correct: there is no main method or structure in Ruby.


1 Answers

You can avoid the need to use semicolons if you use parentheses:

def hello() :hello end 
like image 198
horseyguy Avatar answered Oct 06 '22 14:10

horseyguy