Cody Speroff
Cody Speroff

Reputation: 61

How do I write a function in rails console?

I am trying to write a function in the rails console, and in the example, this is how the function should look in terminal.

>> def string_message(str = '')
>>   return "It's an empty string!" if str.empty?
>>   return "The string is nonempty."
>> end

How do they create a new line while still making the console realize it is all of the lines create a function. Would it be accurate to write it as:

>> def string_message(str = '') \n\t return "It's an empty string!" if str.empty? \n\t blah blah \n\t 

?

Upvotes: 1

Views: 3152

Answers (1)

Nina Satragno
Nina Satragno

Reputation: 601

IRB, the ruby console in which rails console relies supports this out of the box.

Just type your function declaration, press the enter key, then input the body line by line, and finally type end.

You'll see text like this:

2.4.1 :001 > def say_hi(person)
2.4.1 :002?>   puts "Hi #{person}"
2.4.1 :003?>   end
 => :say_hi 
2.4.1 :004 > say_hi("Nina")
Hi Nina
 => nil 
2.4.1 :005 > 

Notice how the ? indicates that IRB is waiting for more input before evaluating the expression.

Upvotes: 3

Related Questions