How to use Ruby return

What is return? ??

How to return the return value of a method. It is classified as a control structure. In Ruby, even if you don't bother to use return, the last processed value will be returned in the defined method.

However, if you want to get out of the process in the middle, you can forcibly return the value by using return.

example

■ When not using return

def total
  price = 1000
  num = 10

  "#{price}Circle clothes#{num}I bought one, so the total is#{price*num}It will be a circle."
  "I returned one, so the total is#{price*(num-1)}It became a circle."
end
p total

result

I returned one, so the total was 9000 yen.

If you do not use return, the last defined wording will be output.

■ When using return

def total
  price = 1000
  num = 10

  return "#{price}Circle clothes#{num}I bought one, so the total is#{price*num}It will be a circle."
  "I returned one, so the total is#{price*(num-1)}It became a circle."
end
p total

result

I bought 10 clothes for 1000 yen, so the total is 10,000 yen.

Using return prints the wording defined after return.

In this way, if you want to exit the process in the middle, you should use return. By the way, I haven't encountered the scene of using return yet ... lol

Recommended Posts

How to use Ruby return
Ruby: How to use cookies
How to use Ruby on Rails
[Ruby] How to use any? Method
How to use Ruby inject method
How to use Map
How to use rbenv
[Ruby on Rails] How to use CarrierWave
How to use letter_opener_web
How to use with_option
How to use fields_for
How to use map
How to use collection_select
Ruby length, size, count How to use
How to use Twitter4J
How to use active_hash! !!
How to use MapStruct
How to use hidden_field_tag
How to use TreeSet
[How to use label]
How to use identity
How to use hashes
[Ruby] How to use slice for beginners
How to use JUnit 5
[Ruby on Rails] How to use redirect_to
[Ruby on Rails] How to use kaminari
How to use Dozer.mapper
How to use Gradle
Ruby: CSV :: How to use Table Note
How to use org.immutables
How to use java.util.stream.Collector
How to use VisualVM
How to use Map
[Ruby] How to use gsub method and sub method
[Ruby on Rails] How to use session method
[Ruby basics] How to use the slice method
[Java] How to use Map
How to use Chain API
[Java] How to use Map
How to use Priority Queuing
[Rails] How to use enum
How to use java Optional
How to use JUnit (beginner)
[Rails] How to use enum
How to use @Builder (Lombok)
[Swift] How to use UserDefaults
How to use java class
How to use Swift UIScrollView
[Ruby] How to comment out
How to use Big Decimal
[Java] How to use Optional ②
[Java] How to use removeAll ()
How to use String [] args
[Java] How to use string.format
How to use rails join
How to use Java Map
Rbenv command to use Ruby
How to use dependent :: destroy
How to use Eclipse Debug_Shell
How to use Apache POI
[Rails] How to use validation