Exercise summary

x = 1
#=> 1
x = x + 1
#=> 2

This might seem really obvious, but it’s worth pointing out: = is an assignment operator; it means ‘set name on the left equal to the value on the right’. It isn’t the same equals as you see in maths! In maths x = x + 1 doesn’t really make sense -it’s an equation with no (finite) solutions. In ruby x = x + 1 makes perfect sense - just set x to be one more than it was before.

b = "hello"
c = b.capitalize

b #=> "hello"
c #=> "Hello"

d = "hello"
e = d.capitalize!

d #=> "Hello"
e #=> "Hello"

This example is pretty important. In the first case capitalize gives back “Hello”, but leaves the original string untouched.

b “hello” c “Hello”

In the second case, we use the in-place version of captialize!. It changes the actual string that d is pointing to, and sets e to point there too. In ruby, methods often come in two flavours like this, with the ! version modifying the original object in place. You could also try out reverse/reverse! and upcase/upcase!.

d e “Hello”
name = "Dave"
#=> "Dave"
f = "Hello #{name}! "
#=> "Hello Dave! "
f
#=> "Hello Dave! "
name = "Sarah"
#=> "Sarah"
f
#=> "Hello Dave! "

The above shows that string interpolation happens when you write it down. When you first write f = "Hello #{name}! " ruby immediately looks up name and bakes it straight into the string. Setting name to something different later on, won’t change this.

In the extra challenge, the expression gave an iterative approximation to sqrt(2). You can tell by rearranging and solving the equation, that any fixed point must be a sqrt of 2. In the final part, by giving it x=1 you forced ruby to do integer arithmetic. If you’re into that sort of thing, you might like to try and find the fixed points in this case!


Prev | Next