0

I have the following method that takes a string and converts the unicode character to an int.

def uni_total(string) string.ord end 

This will total a character. If I wanted to total all of the characters in a string I have tried the following method.

def uni_total(string) string.ord each |item| return item++ end end 

When I run it give me the following error message 'unexpected tIDENTIFIER, expecting keyword_end return item++ What is the best way to get around this? Any help would be appreciated. Regards

3
  • 1
    You should check out this question about ++, the Ruby docs - String#codepoints in particular and also this question to learn how to get the sum of an integer array. Then you end up with a short uni_total implementation: string.codepoints.reduce(:+). Commented Jun 12, 2016 at 21:53
  • 1
    Your question is unclear. What does it mean to "total a combination of characters"? Are you referring to Total Functions? Commented Jun 13, 2016 at 10:42
  • The answer is below . Thanks for the reply. Commented Jun 13, 2016 at 10:46

1 Answer 1

1

Try this

def uni_total(string) acc = 0 string.each_char do |item| acc += item.ord end acc end 

You'll need some accumulator to sum up each char of your string Iterate on each char with each_char method ( string type does not have .each method anymore since Ruby 1.9 ) and then return the accumulator

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.