Results for: "module_function"

Deletes all items from self that are equal to obj.

Returns the last deleted item, or nil if no matching item is found.

If the optional code block is given, the result of the block is returned if the item is not found. (To remove nil elements and get an informative return value, use Array#compact!)

a = [ "a", "b", "b", "b", "c" ]
a.delete("b")                   #=> "b"
a                               #=> ["a", "c"]
a.delete("z")                   #=> nil
a.delete("z") {"not found"}     #=> "not found"

Removes all elements from self.

a = [ "a", "b", "c", "d", "e" ]
a.clear    #=> [ ]

Shuffles elements in self in place.

a = [ 1, 2, 3 ]           #=> [1, 2, 3]
a.shuffle!                #=> [2, 3, 1]
a                         #=> [2, 3, 1]

The optional rng argument will be used as the random number generator.

a.shuffle!(random: Random.new(1))  #=> [1, 3, 2]

Returns a new array with elements of self shuffled.

a = [ 1, 2, 3 ]           #=> [1, 2, 3]
a.shuffle                 #=> [2, 3, 1]
a                         #=> [1, 2, 3]

The optional rng argument will be used as the random number generator.

a.shuffle(random: Random.new(1))  #=> [1, 3, 2]

Choose a random element or n random elements from the array.

The elements are chosen by using random and unique indices into the array in order to ensure that an element doesn’t repeat itself unless the array already contained duplicate elements.

If the array is empty the first form returns nil and the second form returns an empty array.

a = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
a.sample         #=> 7
a.sample(4)      #=> [6, 4, 2, 5]

The optional rng argument will be used as the random number generator.

a.sample(random: Random.new(1))     #=> 6
a.sample(4, random: Random.new(1))  #=> [6, 10, 9, 2]

Calls the given block for each element n times or forever if nil is given.

Does nothing if a non-positive number is given or the array is empty.

Returns nil if the loop has finished without getting interrupted.

If no block is given, an Enumerator is returned instead.

a = ["a", "b", "c"]
a.cycle {|x| puts x}       # print, a, b, c, a, b, c,.. forever.
a.cycle(2) {|x| puts x}    # print, a, b, c, a, b, c.

Allows for declaring a Gemfile inline in a ruby script, optionally installing any gems that aren’t already installed on the user’s system.

@note Every gem that is specified in this ‘Gemfile’ will be ‘require`d, as if

the user had manually called `Bundler.require`. To avoid a requested gem
being automatically required, add the `:require => false` option to the
`gem` dependency declaration.

@param install [Boolean] whether gems that aren’t already installed on the

user's system should be installed.
Defaults to `false`.

@param gemfile [Proc] a block that is evaluated as a ‘Gemfile`.

@example Using an inline Gemfile

#!/usr/bin/env ruby

require 'bundler/inline'

gemfile do
  source 'https://rubygems.org'
  gem 'json', require: false
  gem 'nap', require: 'rest'
  gem 'cocoapods', '~> 0.34.1'
end

puts Pod::VERSION # => "0.34.4"

The primary interface to this library. Use to setup delegation when defining your class.

class MyClass < DelegateClass(ClassToDelegateTo) # Step 1
  def initialize
    super(obj_of_ClassToDelegateTo)              # Step 2
  end
end

Here’s a sample of use from Tempfile which is really a File object with a few special rules about storage location and when the File should be deleted. That makes for an almost textbook perfect example of how to use delegation.

class Tempfile < DelegateClass(File)
  # constant and class member data initialization...

  def initialize(basename, tmpdir=Dir::tmpdir)
    # build up file path/name in var tmpname...

    @tmpfile = File.open(tmpname, File::RDWR|File::CREAT|File::EXCL, 0600)

    # ...

    super(@tmpfile)

    # below this point, all methods of File are supported...
  end

  # ...
end

Produces a shallow copy of obj—the instance variables of obj are copied, but not the objects they reference. dup copies the tainted state of obj.

This method may have class-specific behavior. If so, that behavior will be documented under the #initialize_copy method of the class.

on dup vs clone

In general, clone and dup may have different semantics in descendant classes. While clone is used to duplicate an object, including its internal state, dup typically uses the class of the descendant object to create the new instance.

When using dup, any modules that the object has been extended with will not be copied.

class Klass
  attr_accessor :str
end

module Foo
  def foo; 'foo'; end
end

s1 = Klass.new #=> #<Klass:0x401b3a38>
s1.extend(Foo) #=> #<Klass:0x401b3a38>
s1.foo #=> "foo"

s2 = s1.clone #=> #<Klass:0x401b3a38>
s2.foo #=> "foo"

s3 = s1.dup #=> #<Klass:0x401b3a38>
s3.foo #=> NoMethodError: undefined method `foo' for #<Klass:0x401b3a38>

Returns a list of the names of public and protected methods of obj. This will include all the methods accessible in obj’s ancestors. If the optional parameter is false, it returns an array of obj<i>‘s public and protected singleton methods, the array will not include methods in modules included in <i>obj.

class Klass
  def klass_method()
  end
end
k = Klass.new
k.methods[0..9]    #=> [:klass_method, :nil?, :===,
                   #    :==~, :!, :eql?
                   #    :hash, :<=>, :class, :singleton_class]
k.methods.length   #=> 56

k.methods(false)   #=> []
def k.singleton_method; end
k.methods(false)   #=> [:singleton_method]

module M123; def m123; end end
k.extend M123
k.methods(false)   #=> [:singleton_method]

Looks up the named method as a receiver in obj, returning a Method object (or raising NameError). The Method object acts as a closure in obj’s object instance, so instance variables and the value of self remain available.

class Demo
  def initialize(n)
    @iv = n
  end
  def hello()
    "Hello, @iv = #{@iv}"
  end
end

k = Demo.new(99)
m = k.method(:hello)
m.call   #=> "Hello, @iv = 99"

l = Demo.new('Fred')
m = l.method("hello")
m.call   #=> "Hello, @iv = Fred"

Note that Method implements to_proc method, which means it can be used with iterators.

[ 1, 2, 3 ].each(&method(:puts)) # => prints 3 lines to stdout

out = File.open('test.txt', 'w')
[ 1, 2, 3 ].each(&out.method(:puts)) # => prints 3 lines to file

require 'date'
%w[2017-03-01 2017-03-02].collect(&Date.method(:parse))
#=> [#<Date: 2017-03-01 ((2457814j,0s,0n),+0s,2299161j)>, #<Date: 2017-03-02 ((2457815j,0s,0n),+0s,2299161j)>]

Returns true if int is an odd number.

Returns the angle part of its polar form.

Complex.polar(3, Math::PI/2).arg  #=> 1.5707963267948966

Returns 0 if the value is positive, pi otherwise.

Returns the receiver.

Convert self to locale encoding

Escapes str so that it can be safely used in a Bourne shell command line.

See Shellwords.shellescape for details.

Returns the character length of str.

Makes string empty.

a = "abcde"
a.clear    #=> ""

Produces a version of str with all non-printing characters replaced by \nnn notation and all special characters escaped.

"hello \n ''".dump  #=> "\"hello \\n ''\""

Returns an array of the Integer ordinals of the characters in str. This is a shorthand for str.each_codepoint.to_a.

If a block is given, which is a deprecated form, works the same as each_codepoint.

Returns a copy of str with all characters in the intersection of its arguments deleted. Uses the same rules for building the set of characters as String#count.

"hello".delete "l","lo"        #=> "heo"
"hello".delete "lo"            #=> "he"
"hello".delete "aeiou", "^e"   #=> "hell"
"hello".delete "ej-m"          #=> "ho"

Performs a delete operation in place, returning str, or nil if str was not modified.

Returns 0 if the value is positive, pi otherwise.

Returns the file descriptor used in dir.

d = Dir.new("..")
d.fileno   #=> 8

This method uses dirfd() function defined by POSIX 2008. NotImplementedError is raised on other platforms, such as Windows, which doesn’t provide the function.

Search took: 6ms  ·  Total Results: 3710