Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is ^ used for in ruby? [duplicate]

Tags:

syntax

ruby

Possible Duplicate:
Use of caret symbol( ^ ) in Ruby

So I was playing around with some code and I tried to play around with the power operator. So I thought that perhaps I could use the caret (^) for this purpose, but after using it in:

for i in 0..10
  puts "#{i}   #{1^i}\n"
end

I got some really funky results

0   -  1
1   -  0
2   -  3
3   -  2
4   -  5
5   -  4
6   -  7
7   -  6
8   -  9
9   -  8
10  -  11

The only pattern I see is -1 on an odd number and +1 on an even number, but then when I try:

for i in 0..10
  puts "#{i}   #{2^i}\n"
end

i get:

0   -  2
1   -  3
2   -  0
3   -  1
4   -  6
5   -  7
6   -  4
7   -  5
8   -  10
9   -  11
10  -  8

wth! So then I kept going up to 4^i and plotted them, the 1^i & 3^i came out with decent patterns but 2^i & 4^i were just all over the place with no visible patterns (though highly unlikely) with just 11 plotting points, so I've come to you ladies and gents asking you:

What on earth is ^ used for?!

like image 790
mohsen Avatar asked Jul 13 '12 05:07

mohsen


People also ask

What does DUP do in Ruby?

The dup() is an inbuilt method in Ruby returns the number itself.

How do you copy an object in Ruby?

Ruby does provide two methods for making copies of objects, including one that can be made to do deep copies. The Object#dup method will make a shallow copy of an object. To achieve this, the dup method will call the initialize_copy method of that class. What this does exactly is dependent on the class.

How do you duplicate an object in Rails?

You generally use #clone if you want to copy an object including its internal state. This is what Rails is using with its #dup method on ActiveRecord. It uses #dup to allow you to duplicate a record without its "internal" state (id and timestamps), and leaves #clone up to Ruby to implement.

How do you copy a string in Ruby?

We can use the asterisk * operator to duplicate a string for the specified number of times. The asterisk operator returns a new string that contains a number of copies of the original string.


1 Answers

In most programming languages, ^ is the XOR operator (Exclusive Or in Wikipedia). XOR is one of the most essential operations in the CPU, it often employed to zero registers (think of a ^= a) because it is fast and has a short opcode.

For the power function, you have to use e.g. ** (e.g. in ruby), java.lang.Math.pow, math.pow, pow etc.

In fact, I couldn't name a programming language that uses ^. It is used in LaTeX for formatting (as superscript, not power function, technically). But the two variants I see all the time are ** (as the power function is directly related to multiplication) and pow(base, exp).

Note that you can compute integer powers of 2 faster using shifts.

like image 103
Has QUIT--Anony-Mousse Avatar answered Sep 17 '22 15:09

Has QUIT--Anony-Mousse