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

Wayne Conrad
  • 103,207
  • 26
  • 155
  • 191
AltBrian
  • 2,392
  • 9
  • 29
  • 58
  • 1
    You should check out [this question](https://stackoverflow.com/questions/3660563/why-doesnt-ruby-support-i-or-i-increment-decrement-operators) about `++`, the Ruby docs - [`String#codepoints`](http://ruby-doc.org/core/String.html#method-i-codepoints) in particular and also [this question](https://stackoverflow.com/questions/1538789/how-to-sum-array-of-numbers-in-ruby) to learn how to get the sum of an integer array. Then you end up with a short `uni_total` implementation: `string.codepoints.reduce(:+)`. – cremno Jun 12 '16 at 21:53
  • 1
    Your question is unclear. What does it mean to "total a combination of characters"? Are you referring to [Total Functions](https://wikipedia.org/wiki/Partial_function#Total_function)? – Jörg W Mittag Jun 13 '16 at 10:42
  • The answer is below . Thanks for the reply. – AltBrian Jun 13 '16 at 10:46

1 Answers1

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

Vincent Prigent
  • 119
  • 1
  • 6