Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the returned value from a method from within the method?

Tags:

algorithm

ruby

I've been practicing some algorithms with ruby for a while, and I'm wondering if it is possible to catch the returned value from within the method.

the code below is to reverse a string without any kind of reverse method and with few local variables...

def rev(a)
 i = -1
 a.split("").each do |el|
  el[0] = a[i]
  i = i + (-1)
 end.join
end

Note that the result of the 'each' method is not being assigned to any variable. So, 'each' evaluates to an array with a reversed sequence of characters. At the 'end' (literally) I've just 'called' the method 'join' to glue everything together. The idea is to 'catch' the returned value from all this process and check if is true or false that the reversed string is a palindrome.

If the reversed string is equal to the original one then the word is a palindrome. Ex. "abba", "sexes", "radar"...

for example:

def rev(a)
 i = -1
 a.split("").each do |el|
  el[0] = a[i]
  i = i + (-1)
 end.join
 # catch here the returned value from the code above
 # and check if its a palindrome or not. (true or false)
end

Thank you guys! I will be very grateful if anyone could help me figure out this!

like image 857
Francisco Bach Avatar asked Aug 08 '18 01:08

Francisco Bach


People also ask

How do you find the return value of a method?

You declare a method's return type in its method declaration. Within the body of the method, you use the return statement to return the value. Any method declared void doesn't return a value. It does not need to contain a return statement, but it may do so.

How do I use the return values of a method as parameters of another method in Java?

You just need to assign the return value to a variable of your choice, like String stringReturnValue = someMehtodThatReturnsString(); and then you can use that variable when calling methods eG callSomeOtherMethod(stringReturnValue); .

How do you call a return value from a method in Java?

Some methods return values. To use the return value when calling a method, it must be stored in a variable or used as part of an expression. The variable data type must match the return type of the method.

How do you print a value returned from a method?

To print a value in Python, you call the print() function. Returning is used to return a value from a function and exit the function. To return a value from a function, use the return keyword.


Video Answer


1 Answers

Just add == a to see if your reversal matches the original string:

def rev(a)
 i = -1
 a.split("").each do |el|
  el[0] = a[i]
  i = i + (-1)
 end.join == a
end

puts rev("racecar") # => true
puts rev("racecars") # => false

An easier way to check palindromes (rev could be better named palindrome?) is a == a.reverse since .reverse is essentially what your split/each/join does.

like image 175
ggorlen Avatar answered Sep 30 '22 13:09

ggorlen