Is There an Inverse 'Member' Method in Ruby

Is there an inverse 'member?' method in ruby?

Not in ruby but in ActiveSupport:

characters = ["Konata", "Kagami", "Tsukasa"]
"Konata".in?(characters) # => true

Is there an inversish method for `Array#include?`?

There is no such method in Ruby itself, but there is such method in Rails - Object#in

Is there an opposite function of slice function in Ruby?

Use except:

a = {"foo" => 0, "bar" => 42, "baz" => 1024 }
a.except("foo")
# returns => {"bar" => 42, "baz" => 1024}

Ruby: Is there an opposite of include? for Ruby Arrays?

if @players.exclude?(p.name)
...
end

ActiveSupport adds the exclude? method to Array, Hash, and String. This is not pure Ruby, but is used by a LOT of rubyists.

Source: Active Support Core Extensions (Rails Guides)

Is there a method in Ruby that does the opposite of find?

There is not, but you could create one either the clean-ish way:

a = [0,2,1,0,3]

module Enumerable
def first_not(&block)
find{ |x| !block[x] }
end
end

p a.first_not(&:zero?)
#=> 2

...or the horribly-amusing hack way:

class Proc
def !
proc{ |o,*a| !self[o,*a] }
end
end

p a.find(&!(:zero?.to_proc))
#=> 2

...or the terse-but-terribly-dangerous way:

class Symbol
def !
proc{ |o,*a| !o.send(self,*a) }
end
end

p a.find(&!:zero?)
#=> 2

But I'd advocate just skipping the tricky Symbol#to_proc usage and saying what you want:

p a.find{ |i| !i.zero? }
#=> 2

Is there a built-in inverse cosine function?

According to ruby's math docs the way to use inverse cosine is like this

acos(x) → float

Ruby: How to make a method for additive inverse of an array

sorry, misunderstood your question the first time, the problem here is that puts treat different arrays when you try to show them, you can then use p or print to do what you want, here are the examples

def add_inv_with_puts(x) 
puts x.map {|e| -e}
end
add_inv_with_puts([5,-7,8,3])

def add_inv_with_p(x)
p x.map {|e| -e}
end
add_inv_with_p([5,-7,8,3])

def add_inv_with_print(x)
print x.map {|e| -e}
end
add_inv_with_print([5,-7,8,3])

Find inverse mod in ruby

Brute force for small numbers:

def inv_mod(num, mod)
res = nil
(0..mod).each do |step|
k = (step * mod) + 1
return k / num if k % num == 0
end
res
end

inv_mod(7, 31) # => 9

There should be a faster algorithm over there.



Related Topics



Leave a reply



Submit