Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What do functions with the same name do?

I'm learning ruby and can't for the life of it figure out what this does:

def topic_list
  topics.map(&:name).join(",")
end

def topic_list=(names)
  if names.present?
    topics = names.split(",")
    self.topics = topics.map do |n|
      unless topic = Topic.find_by(slug: n)
        topic = Topic.create!(name: n)
      end
      topic
    end
  end
end

Why would two functions have the same name? Does the first function call the second one?

like image 261
user3188544 Avatar asked Jun 01 '26 16:06

user3188544


1 Answers

topic_list is a getter and topic_list= is a setter method. No they are not the same methods.

This question Trying to learn / understand Ruby setter and getter methods will be helpful as a basic food for this concept. So Read it.

The line self.topics = topics.map... in the method topic_list=, and topics.map(&:name).join(",") line in the method topic_list smells there is one getter called topics and setter topics=. I am sure(If you tell this code works altough) about this by looking at your code.

like image 130
Arup Rakshit Avatar answered Jun 03 '26 06:06

Arup Rakshit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!