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 random
argument will be used as the random number generator:
a.shuffle(random: Random.new(1)) #=> [1, 3, 2]
Returns random elements from self
.
When no arguments are given, returns a random element from self
:
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] a.sample # => 3 a.sample # => 8
If self
is empty, returns nil
.
When argument n
is given, returns a new Array containing n
random elements from self
:
a.sample(3) # => [8, 9, 2] a.sample(6) # => [9, 6, 10, 3, 1, 4]
Returns no more than a.size
elements (because no new duplicates are introduced):
a.sample(a.size * 2) # => [6, 4, 1, 8, 5, 9, 10, 2, 3, 7]
But self
may contain duplicates:
a = [1, 1, 1, 2, 2, 3] a.sample(a.size * 2) # => [1, 1, 3, 2, 1, 2]
The argument n
must be a non-negative numeric value. The order of the result array is unrelated to the order of self
. Returns a new empty Array if self
is empty.
The optional random
argument will be used as the random number generator:
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] a.sample(random: Random.new(1)) #=> 6 a.sample(4, random: Random.new(1)) #=> [6, 10, 9, 2]
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
or:
MyClass = DelegateClass(ClassToDelegateTo) do # 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.
This method may have class-specific behavior. If so, that behavior will be documented under the #initialize_copy
method of the class.
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:0x401be280> s2.foo #=> "foo" s3 = s1.dup #=> #<Klass:0x401c1084> s3.foo #=> NoMethodError: undefined method `foo' for #<Klass:0x401c1084>
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’s public and protected singleton methods, the array will not include methods in modules included in 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.
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 count of characters (not bytes) in self
:
"\x80\u3042".length # => 2 "hello".length # => 5
String#size
is an alias for String#length
.
Related: String#bytesize
.
Returns a printable version of self
, enclosed in double-quotes, with special characters escaped, and with non-printing characters replaced by hexadecimal notation:
"hello \n ''".dump # => "\"hello \\n ''\"" "\f\x00\xff\\\"".dump # => "\"\\f\\x00\\xFF\\\\\\\"\""
Related: String#undump
(inverse of String#dump
).
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.
Deletes the named directory. Raises a subclass of SystemCallError
if the directory isn’t empty.
Deletes the named files, returning the number of names passed as arguments. Raises an exception on any error. Since the underlying implementation relies on the unlink(2)
system call, the type of exception raised depends on its error type (see linux.die.net/man/2/unlink) and has the form of e.g. Errno::ENOENT.
See also Dir::rmdir
.
Returns true
if the named file is readable by the effective user and group id of this process. See eaccess(3).
Note that some OS-level security features may cause this to return true even though the file is not readable by the effective user/group.
Returns true
if the named file is writable by the effective user and group id of this process. See eaccess(3).
Note that some OS-level security features may cause this to return true even though the file is not writable by the effective user/group.
Returns true
if the named file is executable by the effective user and group id of this process. See eaccess(3).
Windows does not support execute permissions separately from read permissions. On Windows, a file is only considered executable if it ends in .bat, .cmd, .com, or .exe.
Note that some OS-level security features may cause this to return true even though the file is not executable by the effective user/group.