Find a mistery number in a equation in Ruby - ruby

So i am learning Ruby and got stuck in one exercise. I need find a mistery number in a equation that is in a string.For example ('10 + ? = 18'). The course i am following ask to use eval. I know eval is dangerous, is just for learning purpose. I am using rspec to test, so dont need use if and return
All i got is this
class MisteryNumber
def calculate(operation)
count = 0
expression = operation.split(' = ')
expression[0].gsub!("?", "#{count}")
(eval(expression[0] - eval(expression[1])
end
end
this code only works if i have subtraction or addition equations. If the equation is like this ('100 / 5 * ? = 40'), doesnt work anymore. I tried to do some form of iterator using gsub(thats why i have the 'count' in the code) but no luck. How i could od this?

I assume that '?' appears at the end of the left side of the equality and that the equation has a solution (the equation is not, for example, ('0 * ? = 1'). Both of these assumptions could be relaxed at the expense of somewhat more complex code. I will leave it to the reader to make those adjustments if desired.
We can write the main method as follows.
def calc(str)
str = str.gsub(/[ =]/, '')
(str = str.insert(0,'+')) if str.match?(/\A\d/)
left_str, s, right_str = str.partition(/[\+\-\/\*]\?/)
qop = s[0]
left_str = reduce_left(left_str)
coeff, right_val = shift_to_right(left_str, right_str.to_f)
solve(coeff, right_val, qop)
end
For example,
calc "3 * 7 / 3 + 4 / 2 * ? = 12"
#=> 2.5
calc "2 - 4 / 2 + 8 / 2 + ? = 20"
#=> 16.0
Suppose
str = "3 * 7 / 3 + 4 / 2 * ? = 12"
The first two steps are to adjust the formatting to simplify the following operations.
str = str.gsub(/[ =]/, '')
#=> "3*7/3+4/2*?12"
(str = str.insert(0,'+')) if str.match?(/\A\d/)
#=> "+3*7/3+4/2*?12"
Now we break the string into three pieces.
left_str, s, right_str = str.partition(/[\+\-\/\*]\?/)
#=> ["+3*7/3+4/2", "*?", "12"]
so
left_str
#=> "+3*7/3+4/2"
s #=> "*?"
right_str
#=> "12"
and save for later:
qop = s[0]
#=> "*"
The three regular expressions read as follows.
/[ =]/: match a space or equals sign
/\A\d/: match a digit at the beginning of the string
/[\+\-\/\*]\?/: match a '+', '-', '/' or '*'
The next step is to remove '*' and '/' from left_str. We can do this iteratively until none remain. The following method removes one. This uses the following regular expression:
R = /(\d+(?:\.\d+)?)([\*\/])(\d+(?:\.\d+)?)/
We can write this regular expression in free-spacing mode to make it self-documenting.
R = /
( # begin capture group 1
\d+ # match 1+ digits
(?:\.\d+) # match period followed by 1+ digits in a non-capture group
? # make the non-capture group optional
) # end capture group 1
( # begin the capture group 2
[\*\/] # match one character in the character class
) # end capture group 2
( # begin capture group 3
\d+ # match 1+ digits
(?:\.\d+) # match period followed by 1+ digits in a non-capture group
? # make the non-capture group optional
) # end capture group 3
/x # invoke free-spacing regex definition mode
def reduce_left_once(left_str)
left_str.gsub(R) { $1.to_f.public_send($2, $3.to_f) }
end
Note that m is a MatchData object.
We can test (where left_str #=> "+3*7/3+4/2"):
left_str = reduce_left_once(left_str)
#=> "+21.0/3+2.0"
left_str = reduce_left_once(left_str)
#=> "+7.0+2.0"
left_str = reduce_left_once(left_str)
#=> "+7.0+2.0"
As no change was made in the last step we are finished with this operation. This can be operationalized with the following method.
def reduce_left(left_str)
loop do
new_left_str = reduce_left_once(left_str)
break left_str if left_str == new_left_str
left_str = new_left_str
end
end
left_str = "+3*7/3+4/2"
left_str = reduce_left(left_str)
#=> "+7.0+2.0"
The next step is to shift all terms but the last in left_str to the right of the equality and adjust the right side accordingly. If qop equals '*' or '/' the last term of left_str is '?''s coefficient; else it will be shifted to the right in the last step.
def shift_to_right(left_str, right_val)
*terms, coeff = left_str.scan(/[\+\-]\d+/)
terms.each { |s| right_val -= s.to_f }
[coeff.to_f, right_val]
end
left_str = "+7.0+2.0"
right_str = "12"
coeff, right_val = shift_to_right(left_str, right_str.to_f)
#=> [2.0, 5.0]
So
coeff
#=> 2.0
right_val
#=> 5.0
At this point we have reduced the original expression to
2.0 * x = 5.0
and need to solve for x.
The regular expression /[\+\-]\d+/ in shift_to_right matches '+' or '-' followed by one or more digits.
The last step is to solve this simple linear equation. Recall that we have computed right_val #=> "12" and '?''s operator is given by qop #=> "*".
def solve(coeff, right_val, qop)
case qop
when '+' then right_val - coeff
when '-' then coeff - right_val
when '*' then right_val/coeff
else right_val * coeff
end
end
solve(coeff, right_val, qop)
#=> 2.5
Note that most of these operations would be needed if eval were used.

Firstly: what sort of course is it?! This is definitely not a task for beginners!
One option to solve this without a parser is using approximations. It will not work for all the possible equation, but will 100% work when the difference of left and right sides is a monotonic, continuous function and has a good chance working for a good part of not-monotonic but continuous functions as well.
left, right = operation.split('=')
.map {|side| side.gsub('?', 'x')}
.map {|str| ->(x) { eval str }}
diff = ->(x) { left.(x) - right.(x) }
The above code will transform given equation into two procs representing left and right side of the equation. We are now looking for such x that diff.(x) == 0.
Next we need to find any two numbers for which diff.(a) * diff.(b) < 0, so that diff.(a) and diff.(b) have different signs. I'd probably start from some reasonable start test numbers (might depend on the common examples given), like [0, 1]. If diff.(0) and diff.(1) have different sign, we move to next step, if not we move the boundaries (preferably exponentially) until we find such numbers. NOTE: as the equation might have no solutions,diff >= 0. However, the proposed approach will work for any monotonic, continuous functions.
Step 2. Having [a,b] such that diff.(a) and diff.(b) we basically start a binary search. We calculate diff.((a+b)/2) and, depending on its sign, we take either a or b so that new pair have opposite signs. We repeat the process until diff.((a+b)/2) is zero. If that was just maths, we would need to establish some precision, but here we already have precision of float, so we can assume that it will eventually happen.
So, this would be the process, I'll leave coding it to you. :) Good luck. And seriously, what course is it?

Related

Ruby - Find the longest non-repeating substring in any given string

I am working on an assignment where I have to take user input of a string and search through it to find the longest non-repeating string in it. So for example:
If the string is:
"abcabcabcdef"
My output needs to be:
"abcdef is the longest substring at the value of 6 characters"
Here is my poorly made code:
class Homework_4
puts "Enter any string of alphabetical characters: "
user_input = gets
longest_str = 0
empty_string = ""
map = {}
i = 0
j = 0
def long_substr()
while j < str_len
if map.key?(user_input[j])
i = [map[user_input[j]], i].max
end
longest_str = [longest_str, j - i + 1].max
map[user_input[j]] = j + 1
j += 1
end
longest_str
end
long_substr(user_input)
end
I have been working on this for over 6 hours today and I just can't figure it out. It seems like the internet has many ways to do it. Almost all of them confuse me greatly and don't really explain what they're doing. I don't understand the syntax they use or any of the variables or conditions.
All I understand is that I need to create two indicators that go through the inputted string searching for a non-repeating substring (sliding window method). I don't understand how to create them, what to make them do or even how to make them find and build the longest substring. It is very confusing to try and read the code that is full of random letters, symbols, and conditions. I'm sure my code is all sorts of messed up but any help or tips that could point me in the right direction would be greatly appreciated!
def uniq?(s)
# All letters of s uniq?
return s.chars.uniq == s.chars
end
def subs(s)
# Return all substrings in s.
(0..s.length).inject([]){|ai,i|
(i..s.length - i).inject(ai){|aj,j|
aj << s[i,j]
}
}.uniq
end
def longest_usub(s)
# Return first longest substring of s.
substrings(s).inject{|res, s| (uniq?(s) and s.length > res.length) ? s : res}
end
ruby's inject is actually a reduce function, where inject(optional_start_value){<lambda expression>} - and the lambda expression is similar to Python's lambda x, y: <return expression using x and y> just that lambda expressions are strangely written in Ruby as {|x, y| <return expression using x and y>}.
Python's range(i, y) is Ruby's i..y.
Python's slicing s[i:j] is in Ruby s[i..j] or s[i,j].
<< means add to end of the array.
Second solution (inspired by #Rajagopalan's answer)
def usub(s)
# Return first chunk of uniq substring in s
arr = []
s.chars do |char|
break if arr.include? char
arr << char
end
arr.join
end
def usubs(s)
# Return each position's usub() in s
(0..s.length).to_a.map{|i| usub(s[i,s.length])}
end
def longest_usub(s)
# return the longest one of the usubs() over s
usubs(s).max_by(&:length)
end
then you can do:
longest_usub("abcabcabcdef")
## "abcdef"
I have asssumed that a string is defined to be repeating if it contains a substring s of one or one more characters that is followed by the same substring s, and that a string is non-repeating if it is not repeating.
A string is seen to be repeating if and only if it matches the regular expression
R = /([a-z]+)\1/
Demo
The regular expression reads, "match one or more letters that are saved to capture group one, then match the content of capture group 1".
For convenience we can construct a simple helper method.
def nonrepeating?(str)
!str.match? R
end
I will perform a binary search to find the longest non-repeating string. First, I need a second helper method:
def find_nonrepeating(str, len)
0.upto(str.size-len) do |i|
s = str[i,len]
return s if nonrepeating?(s)
end
nil
end
find_nonrepeating("abababc", 7) #=> nil
find_nonrepeating("abababc", 6) #=> nil
find_nonrepeating("abababc", 5) #=> nil
find_nonrepeating("abababc", 4) #=> "babc"
find_nonrepeating("abababc", 3) #=> "aba"
find_nonrepeating("abababc", 2) #=> "ab"
find_nonrepeating("abababc", 1) #=> "a"
We may now implement the binary search.
def longest(str)
longest = ''
low = 0
high = str.size - 1
while low < high
mid = (low + high)/2
s = find_nonrepeating(str, mid)
if s
longest = s
low = mid + 1
else
high = mid - 1
end
end
longest
end
longest("dabcabcdef")
#=> "bcabcdef"
a = "abcabcabcdef"
arr = []
words = []
b=a
a.length.times do
b.chars.each do |char|
break if arr.include? char
arr << char
end
words << arr.join
arr.clear
b=b.chars.drop(1).join
end
p words.map(&:chars).max_by(&:length).join
Output
"abcdef"

Capitalize every nth character of each word in a string in Ruby

I need to capitalize every 'nth' character for each word in a string (every multiple of 4-th character in this example, so character 4, 8, 12 etc).
I came up with the code below (not very elegant I know!) but it only works for words which length < 8.
'capitalize every fourth character in this string'.split(' ').map do |word|
word.split('').map.with_index do |l,idx|
idx % 3 == 0 && idx > 0 ? word[idx].upcase : l
end
.join('')
end
.flatten.join(' ')
Anybody could show me how to capitalize every 4th character in words which length > 8?
Thanks!
str = 'capitalize every fourth character in this string'
idx = 0
str.gsub(/./) do |c|
case c
when ' '
idx = 0
c
else
idx += 1
(idx % 4).zero? ? c.upcase : c
end
end
#=> "capItalIze eveRy fouRth chaRactEr in thiS strIng"
As an option, you can just modify the nth character in the string if it exists by accessing the character by index:
'capitalizinga every fourth character in this string'.split(' ').map do |word|
(3..word.length).step(4) do |x|
c = word[x]
word[x] = c.upcase if c
end
word
end.join(' ')
# capItalIzinGa eveRy fouRth chaRactEr in thiS strIng
Here is the method step or Range class is used, so each fourth index could be calculated: 3, 7, 11, etc...
I think the easiest way is to use a regex with substitution:
'capitalize every fourth character in this string'
.gsub(/([\w]{3})(\w)|([\w]{1,3})/) {
"#{$1}#{$2.to_s.upcase}#{$3}"
}
# => capItalIze eveRy fouRth chaRactEr in thiS strIng
This uses 2 alternatives with captured groups - the first alternative matches 4 characters and the second everything with 1 to 3 characters. Group $1 will match exactly three letters and group $2 the fourth letter within a 4-letter block - while group $3 will match remainders of a longer word as well words shorter than 4 characters.
You can then replace group $2 globally with gsub. Also you need to do $2.to_s in case $2 is nil (or catch that scenario with a ternary operator).
You can inspect the regex here and try the code here
> str.split(" ").map{|word|
word.chars.each_with_index{|c,i|
c.upcase! if (i > 0 && (i+1)%4 == 0)}.join}.join(" ")
#=> "capItalIze eveRy fouRth chaRactEr in thiS strIng"
def capitalize_each_nth_char(str, n)
str.chars.each_slice(n).to_a.each { |arr| arr[-1] = arr[-1].upcase if arr.size == n }.join('')
end
Here is the explanation,
str.chars # will give array of characters
str.chars.each_slice(n) # will give an enumerator as, #<Enumerator: ...>
str.chars.each_slice(n).to_a # will give an array of arrays
arr[-1].upcase # it will capitalize the last element i.e. 4th element of each array
if arr.size == n # it will prevent to capitalize last element of sub-array if it's size is less than n(in our case 4)
str.chars.each_slice(n).to_a.each { |arr| arr[-1] = arr[-1].upcase if arr.size == n } # it will give array of subarray where every subarray last element is capital
str.chars.each_slice(n).to_a.each { |arr| arr[-1] = arr[-1].upcase if arr.size == n }.join('') # it will give the final result as, "capItalIze EverY foUrth chaRactEr iN thIs sTrinG"

Algorithm to print all valid combations of n pairs of parenthesis

I'm working on the problem stated in the question statement. I know my solution is correct (ran the program) but I'm curious as to whether or not I'm analyzing my code (below) correctly.
def parens(num)
return ["()"] if num == 1
paren_arr = []
parens(num-1).each do |paren|
paren_arr << paren + "()" unless "()#{paren}" == "#{paren}()"
paren_arr << "()#{paren}"
paren_arr << "(#{paren})"
end
paren_arr
end
parens(3), as an example, will output the following:
["()()()", "(()())", "(())()", "()(())", "((()))"]
Here's my analysis:
Every f(n) value is roughly 3 times as many elements as f(n-1). So:
f(n) = 3 * f(n-1) = 3 * 3 * f(n-2) ~ (3^n) time cost.
By a similar analysis, the stack will be occupied by f(1)..f(n) and so the space complexity should be 3^n.
I'm not sure if this analysis for either time or space is correct. On the one hand, the stack only holds n function calls, but each of these calls returns an array ~3 times as big as the call before it. Does this factor into space cost? And is my time analysis correct?
As others have mentioned, your solution is not correct.
My favourite solution to this problem generates all the valid combinations by repeatedly incrementing the current string to the lexically next valid combination.
"Lexically next" breaks down into a few rules that make it pretty easy:
The first difference in the string changes a '(' to a ')'. Otherwise the next string would be lexically before the current one.
The first difference is as far to the right as possible. Otherwise there would be smaller increments.
The part after the first difference is lexically minimal, again because otherwise there would be smaller increments. In this case that means that all the '('s come before all the ')'.
So all you have to do is find the rightmost '(' that can be changed to a ')', flip it, and then append the correct number of '('s and ')'s.
I don't know Ruby, but in Python it looks like this:
current="(((())))"
while True:
print(current)
opens=0
closes=0
pos=0
for i in range(len(current)-1,-1,-1):
if current[i]==')':
closes+=1
else:
opens+=1
if closes > opens:
pos=i
break
if pos<1:
break
current = current[:pos]+ ")" + "("*opens + ")"*(closes-1)
Output:
(((())))
((()()))
((())())
((()))()
(()(()))
(()()())
(()())()
(())(())
(())()()
()((()))
()(()())
()(())()
()()(())
()()()()
Solutions like this turn out to be easy and fast for many types of "generate all the combinations" problems.
Recursive reasoning makes a simple solution. If the number of left parens remaining to emit is positive, emit one and recur. If the number of right parens remaining to emit is greater than the number of left, emit and recur. The base case is when all parens, both left and right, have been emitted. Print.
def parens(l, r = l, s = "")
if l > 0 then parens(l - 1, r, s + "(") end
if r > l then parens(l, r - 1, s + ")") end
if l + r == 0 then print "#{s}\n" end
end
As others have said, the Catalan numbers give the number of strings that will be printed.
While this Ruby implementation doesn't achieve it, a lower level language (like C) would make it easy to use a single string buffer: O(n) space. Due to substring copies, this one is O(n^2). But since the run time and output length are O(n!), O(n) space inefficiency doesn't mean much.
I found Tom Davis' article, "Catalan Numbers," very helpful in explaining one recursive method for defining the Catalan Numbers. I'll try to explain it myself (in part, to see how much of it I've understood) as it may be applied to finding the set of all unique arrangements of N matched parentheses (e.g., 1 (); 2 ()(), (()); etc. ).
For N > 1 let (A)B represent one arrangement of N matched parentheses, where A and B each have only balanced sets of parentheses. Then we know that if A contains k matched sets, B must have the other N - k - 1, where 0 <= k <= N - 1.
In the following example, a dot means the group has zero sets of parentheses:
C_0 => .
C_1 => (.)
To enumerate C_2, we arrange C_1 as AB in all ways and place the second parentheses around A:
. () = AB = C_0C_1 => (.)()
() . = AB = C_1C_0 => (()) .
Now for C_3, we have three partitions for N - 1, each with its own combinations: C_0C_2, C_1C_1, C_2C_0
C_0C_2 = AB = . ()() and . (()) => ()()(), ()(())
C_1C_1 = AB = ()() => (())()
C_2C_0 = AB = ()() . and (()) . => (()()), ((()))
We can code this method by keeping a set for each N and iterating over the combinations for each partition. We'll keep the individual arrangements as bits: 0 for left and 1 for right (this appears backwards when cast as a binary string).
def catalan
Enumerator.new do |y|
# the zero here represents none rather than left
s = [[0],[2]]
y << [0]
y << [2]
i = 2
while true
s[i] = []
(0..i - 1).each do |k|
as = s[k]
bs = s[i - k - 1]
as.each do |a|
bs.each do |b|
if a != 0
s[i] << ((b << (2*k + 2)) | (1 << (2*k + 1)) | (a << 1))
else
s[i] << (2 | (b << 2))
end
end # bs
end # as
end # k
y.yield(s[i])
i = i + 1
end # i
end # enumerator
end
catalan.take(4)
# => [[0], [2], [10, 12], [42, 50, 44, 52, 56]]
The yielder is lazy: although the list is infinite, we can generate as little as we like (using .take for example):
catalan.take(4).last.map{|x| x.to_s(2)}
# => ["101010", "110010", "101100", "110100", "111000"]
The former generation obliges us to keep all previous sets in order to issue the next. Alternatively, we can build a requested set through a more organic type, meandering recursion. This next version yields each arrangement to the block, so we can type:
catalan(4){
|x| (0..7).reduce(""){
|y,i| if x[i] == 0 then y + "(" else y + ")" end
}
}.take(14)
# => ["(((())))", "((()()))", "((())())", "((()))()", "(()(()))", "(()()())",
# "(()())()", "(())(())", "(())()()", "()((()))", "()(()())", "()(())()",
# "()()(())", "()()()()"]
Direct generation:
def catalan(n)
Enumerator.new do |y|
s = [[0,0,0]]
until s.empty?
left,right,result = s.pop
if left + right == 2 * n
y << yield(result)
end
if right < left
s << [left, right + 1, result | 1 << (left + right)]
end
if left < n
s << [left + 1, right, result]
end
end
end
end

I don't understand this method

I'm a beginner in Ruby and I don't understand what this code is doing, could you explain it to me, please?
def a(n)
s = 0
for i in 0..n-1
s += i
end
s
end
def defines a method. Methods can be used to run the same code on different values. For example, lets say you wanted to get the square of a number:
def square(n)
n * n
end
Now I can do that with different values and I don't have to repeat n * n:
square(1) # => 1
square(2) # => 4
square(3) # => 9
= is an assignment.
s = 0 basically says, behind the name s, there is now a zero.
0..n-1 - constructs a range that holds all numbers between 0 and n - 1. For example:
puts (0..3).to_a
# 0
# 1
# 2
# 3
for assigns i each consecutive value of the range. It loops through all values. So first i is 0, then 1, then ... n - 1.
s += i is a shorthand for s = s + i. In other words, increments the existing value of s by i on each iteration.
The s at the end just says that the method (remember the thing we opened with def) will give you back the value of s. In other words - the sum we accumulated so far.
There is your programming lesson in 5 minutes.
This example isn't idiomatic Ruby code even if it is syntactically valid. Ruby hardly ever uses the for construct, iterators are more flexible. This might seem strange if you come from another language background where for is the backbone of many programs.
In any case, the program breaks down to this:
# Define a method called a which takes an argument n
def a(n)
# Assign 0 to the local variable s
s = 0
# For each value i in the range 0 through n minus one...
for i in 0..n-1
# ...add that value to s.
s += i
end
# The result of this method is s, the sum of those values.
s
end
The more Ruby way of expressing this is to use times:
def a(n)
s = 0
# Repeat this block n times, and in each iteration i will represent
# a value in the range 0 to n-1 in order.
n.times do |i|
s += i
end
s
end
That's just addressing the for issue. Already the code is more readable, mind you, where it's n.times do something. The do ... end block represents a chunk of code that's used for each iteration. Ruby blocks might be a little bewildering at first but understanding them is absolutely essential to being effective in Ruby.
Taking this one step further:
def a(n)
# For each element i in the range 0 to n-1...
(0..n-1).reduce |sum, i|
# ...add i to the sum and use that as the sum in the next round.
sum + i
end
end
The reduce method is one of the simple tools in Ruby that's quite potent if used effectively. It allows you to quickly spin through lists of things and compact them down to a single value, hence the name. It's also known as inject which is just an alias for the same thing.
You can also use short-hand for this:
def a(n)
# For each element in the range 0 to n-1, combine them with +
# and return that as the result of this method.
(0..n-1).reduce(&:+)
end
Where here &:+ is shorthand for { |a,b| a + b }, just as &:x would be short for { |a,b| a.x(b) }.
As you are a beginner in Ruby, let's start from the small slices.
0..n-1 => [0, n-1]. E.g. 0..3 => 0, 1, 2, 3 => [0, 3]
for i in 0.. n-1 => this is a for loop. i traverses [0, n-1].
s += i is same as s = s + i
So. Method a(n) initializes s = 0 then in the for loop i traverse [0, n - 1] and s = s + i
At the end of this method there is an s. Ruby omits key words return. so you can see it as return s
def a(n)
s = 0
for i in 0..n-1
s += i
end
s
end
is same as
def a(n)
s = 0
for i in 0..n-1
s = s + i
end
return s
end
a(4) = 0 + 1 + 2 + 3 = 6
Hope this is helpful.
The method a(n) calculates the sums of the first n natural numbers.
Example:
when n=4, then s = 0+1+2+3 = 6
Let's go symbol by symbol!
def a(n)
This is the start of a function definition, and you're defining the function a that takes a single parameter, n - all typical software stuff. Notably, you can define a function on other things, too:
foo = "foo"
def foo.bar
"bar"
end
foo.bar() # "bar"
"foo".bar # NoMethodError
Next line:
s = 0
In this line, you're both declaring the variable s, and setting it's initial value to 0. Also typical programming stuff.
Notably, the value of the entire expression; s = 0, is the value of s after the assignment:
s = 0
r = t = s += 1 # You can think: r = (t = (s += 1) )
# r and t are now 1
Next line:
for i in 0..n-1
This is starting a loop; specifically a for ... in ... loop. This one a little harder to unpack, but the entire statement is basically: "for each integer between 0 and n-1, assign that number to i and then do something". In fact, in Ruby, another way to write this line is:
(0..n-1).each do |i|
This line and your line are exactly the same.
For single line loops, you can use { and } instead of do and end:
(0..n-1).each{|i| s += i }
This line and your for loop are exactly the same.
(0..n-1) is a range. Ranges are super fun! You can use a lot of things to make up a range, particularly, time:
(Time.now..Time.new(2017, 1, 1)) # Now, until Jan 1st in 2017
You can also change the "step size", so that instead of every integer, it's, say, every 1/10:
(0..5).step(0.1).to_a # [0.0, 0.1, 0.2, ...]
Also, you can make the range exclude the last value:
(0..5).to_a # [0, 1, 2, 3, 4, 5]
(0...5).to_a # [0, 1, 2, 3, 4]
Next line!
s += i
Usually read aloud a "plus-equals". It's literally the same as: s = s + 1. AFAIK, almost every operator in Ruby can be paired up this way:
s = 5
s -= 2 # 3
s *= 4 # 12
s /= 2 # 6
s %= 4 # 2
# etc
Final lines (we'll take these as a group):
end
s
end
The "blocks" (groups of code) that are started by def and for need to be ended, that's what you're doing here.
But also!
Everything in Ruby has a value. Every expression has a value (including assignment, as you saw with line 2), and every block of code. The default value of a block is the value of the last expression in that block.
For your function, the last expression is simply s, and so the value of the expression is the value of s, after all is said and done. This is literally the same as:
return s
end
For the loop, it's weirder - it ends up being the evaluated range.
This example may make it clearer:
n = 5
s = 0
x = for i in (0..n-1)
s += i
end
# x is (0..4)
To recap, another way to write you function is:
def a(n)
s = 0
(0..n-1).each{ |i| s = s + i }
return s
end
Questions?

How did "print i[-1]" wrap from z to a in this caesar cipher code?

Like the title says, why do we use "print i[-1]" in this code?
def caesar_cipher (string, number)
string.scan (/./) do |i|
if ("a".."z").include? (i.downcase) # Identify letters only.
number.times {i = i.next}
end
print i[-1] # Wrap from z to a.
end
end
caesar_cipher("Testing abzxc.", 5)
I understand all of the code except that particular line. How was ruby able to wrap Z to A? I mean look at this code:
test1 = "z"
puts test1[-1]
# result is Z not A
I was expecting the result to be A but the result is Z. Can someone explain what am I missing here?
If the input is "z", the caesar_cipher("z", 5) will call the i = i.next 5 times, which moves i to the 5th element followed.
i = "z"
i = i.next # aa
i = i.next # ab
i = i.next # ac
i = i.next # ad
i = i.next # ae
Now, the i[-1] will extract the last character from the result, and discard the leading carry a.
See String#[]:
test1[-1] returns the last letter of the string. Since the last letter of string "z" is "z", it returns it.

Resources