Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to implement 1+1=3 in Ruby [duplicate]

Tags:

ruby

I am feeling that following solution

class Fixnum   def +(x)     self + x + 1   end end 

should not work, since + will be called recursively.

like image 583
Huang Minghe Avatar asked Mar 12 '15 07:03

Huang Minghe


People also ask

How do you check if there are duplicates in an array Ruby?

select { array. count } is a nested loop, you're doing an O(n^2) complex algorithm for something which can be done in O(n). You're right, to solve this Skizit's question we can use in O(n); but in order to find out which elements are duplicated an O(n^2) algo is the only way I can think of so far.

What does .uniq do in Ruby?

uniq is a Ruby method that returns a new array by removing duplicate elements or values of the array.

How do I merge two arrays in Ruby?

This can be done in a few ways in Ruby. The first is the plus operator. This will append one array to the end of another, creating a third array with the elements of both. Alternatively, use the concat method (the + operator and concat method are functionally equivalent).

What does .first mean in Ruby?

The first() is an inbuilt method in Ruby returns an array of first X elements. If X is not mentioned, it returns the first element only. Syntax: range1.first(X) Parameters: The function accepts X which is the number of elements from the beginning. Return Value: It returns an array of first X elements.


1 Answers

Using alias to store the original + like this works:

class Fixnum   alias old_plus +   def +(x)     old_plus(x).succ   end end 
like image 190
Yu Hao Avatar answered Sep 20 '22 01:09

Yu Hao