Ruby method without arguments

I am quite new to Ruby and am struggling with the concept of making your
own method when this method doesn’t take an argument.

This following example is clear to me:

def hello
puts “hello”
end

However, where I get confused is where you have to manipulate input when
a method does not take an argument.

An example would be if you wanted to write a method called count_str
that returns a count of characters in a string - i.e. “Paul”.count_str=
4

I am confused as to how you can create a method to return a value
without taking a value as an argument.

I know this could be done by using (string) as an argument:

def count(string)
puts string.length
end
count(“Paul”)

Can someone help with this please and explain how you can access the
object you want to invoke the method on if it is not accepted as an
argument?

Paul F. wrote in post #1166996:

Can someone help with this please and explain how you can access the
object you want to invoke the method on if it is not accepted as an
argument?

You place the method in the object’s class - either the regular one or
the singleton class:

irb(main):001:0> s = “Paul”
=> “Paul”
irb(main):002:0> s.class
=> String
irb(main):003:0> class String; def count_str; scan(/./).size end end
=> nil
irb(main):004:0> s.count_str
=> 4
irb(main):005:0> “foo”.count_str
=> 3

Ruby version 2.0.0
irb(main):001:0> s = “Paul”
=> “Paul”
irb(main):002:0> def s.count_str; scan(/./).size end
=> nil
irb(main):003:0> s.count_str
=> 4
irb(main):004:0> “foo”.count_str
NoMethodError: undefined method count_str' for "foo":String from (irb):4 from /usr/bin/irb:12:in

However, modifying such central classes as String should be done with
care as the potential to wreck havoc on a large code base is there.

Kind regards

robert

that’s great, thank you Robert.

The evaluation of the last line of a method is what the method will
return. So you can catch the returned value by doing something like
this.

def give_me_some_random_number
Random.rand
end

a_random_number = give_me_some_random_number()

Easy as that.
Robert explained that aspect really good, here’s is another point of
view since your question is not very clear.