There are several things to add in your code:
- Instead
String.new, you can simply add your string within quotes.
str.split("") can be str.chars.
$j = $j + 1 can be $j += 1.
- If you're doing a comparison between
$j and $n then << should be <.
- You don't need
; unless you're writing all in one line.
begin; end while can be just while; end
I guess it could be like:
n = gets.to_i
s = 'abc'
s.split('').each do |i|
j = 0
x = i
while j < n
x = x.next
j += 1
end
puts x
end
But you could use String#ord over each char in your string to return the ordinal of it, add the user input and then String#chr to get the ASCII character for that number:
# With n being the user's input as integer, in this case 3.
p 'abc'.chars.map { |char| (char.ord + n).chr }.join
# "def"
Added n = gets.to_i as stated in the comments by @Ganesh.
If looking for a Caesar Cipher implementation:
def foo(string, n)
lower = ('a'..'z').to_a.join
upper = ('A'..'Z').to_a.join
string.tr(lower + upper, lower[n..-1] + lower[0...n] + upper[n..-1] + upper[0...n])
end
p foo('XYZ', 1) # "YZA"
p foo('ABC', 1) # "BCD"
p foo('ABC', 3) # "DEF"
Slower, but...
<<be<?$n=gets.to_i. See the repl.'xyz'etc?