[Ruby] When you want to use the method outside

1 minute read

【Overview】


1. Conclusion

2. What is a method

3. How to use

4.Another solution

  1. Conclusion

    Use instance variables and methods!


  1. What is a method

    “A determined method to achieve the purpose. Method. Method”

But in a nutshell, it can be used by attaching it to a variable (instance method) or an existing method such as an equation (length, each, times, etc.)!

When used outside, the concept of scope comes out I wrote a little in the article below!

Difference between variables and instance variables

  1. How to use

    Then what actually happens is as follows.

Relationship between instance method and instance variable


class Student

 def initialize(gender, height, personality)
  @gender = gender
  @height = height
  @personality = personality
 end

 def gender
  @gender
 end

 def height
  @height
 end

 def personality
  @personality
 end

end

student = Student.new("male", "175cm", "friendly")
puts "Gender: #{student.gender} Height: #{student.height} Personality: #{student.personality}"

By doing this, you can freely attach a method to the variable It can also be used outside of “def end” (beyond the scope)!


  1. Another solution

    You can write the same thing in the method!

Complete in method


class student

def initialize(gender, height, personality)
  @gender = gender
  @height = height
  @personality = personality
  puts "Gender:#{@gender} Height:#{@height}# Personality:#{@personality}"
end

student = Student.new("male", "175cm", "friendly")

You can still use it in a method this way!