KellysOnTop23
KellysOnTop23

Reputation: 1435

why .times is being difficult - Ruby

Can someone please explain to me why the Ruby function .times is being difficult

str.chars.map{|letter| num.times{letter.next}}

is producing just the number (num) for however many letters were in the word instead of moving each letter down the alphabet (.next) that many times. I know it seems simple but from what i understand of .times this is the way to use it but something like this has happened many.times....that was a joke.

Upvotes: 1

Views: 62

Answers (3)

Mladen Jablanović
Mladen Jablanović

Reputation: 44100

> 'abc'.chars.map{|c| c.tap { 3.times{c.next!} } }.join
=> "def"

or perhaps

3.times.inject(letter){|a,_| a.next}

but neither is very readable.

Upvotes: 0

Luke
Luke

Reputation: 2063

Yeah I'd do something like

def caesar_up(string, n)
  string.chars.map { |char| (char.ord + n).chr }.join
end

Then use it like caesar_up("MOM", 2) to get "OQO"

Upvotes: 0

Wand Maker
Wand Maker

Reputation: 18762

num.times returns the value of num. You should use something like below:

str.chars.map{|letter| num.times{ letter = letter.next }; letter }

Upvotes: 1

Related Questions