Results for: "Array"

When max is an Integer, rand returns a random integer greater than or equal to zero and less than max. Unlike Kernel.rand, when max is a negative integer or zero, rand raises an ArgumentError.

prng = Random.new
prng.rand(100)       # => 42

When max is a Float, rand returns a random floating point number between 0.0 and max, including 0.0 and excluding max.

prng.rand(1.5)       # => 1.4600282860034115

When range is a Range, rand returns a random number where range.member?(number) == true.

prng.rand(5..9)      # => one of [5, 6, 7, 8, 9]
prng.rand(5...9)     # => one of [5, 6, 7, 8]
prng.rand(5.0..9.0)  # => between 5.0 and 9.0, including 9.0
prng.rand(5.0...9.0) # => between 5.0 and 9.0, excluding 9.0

Both the beginning and ending values of the range must respond to subtract (-) and add (+)methods, or rand will raise an ArgumentError.

Seeds the system pseudo-random number generator, with number. The previous seed value is returned.

If number is omitted, seeds the generator using a source of entropy provided by the operating system, if available (/dev/urandom on Unix systems or the RSA cryptographic provider on Windows), which is then combined with the time, the process id, and a sequence number.

srand may be used to ensure repeatable sequences of pseudo-random numbers between different runs of the program. By setting the seed to a known value, programs can be made deterministic during testing.

srand 1234               # => 268519324636777531569100071560086917274
[ rand, rand ]           # => [0.1915194503788923, 0.6221087710398319]
[ rand(10), rand(1000) ] # => [4, 664]
srand 1234               # => 1234
[ rand, rand ]           # => [0.1915194503788923, 0.6221087710398319]

Returns a random number using the Ruby system PRNG.

See also Random#rand.

Returns a string, using platform providing features. Returned value is expected to be a cryptographically secure pseudo-random number in binary form. This method raises a RuntimeError if the feature provided by platform failed to prepare the result.

In 2017, Linux manpage random(7) writes that “no cryptographic primitive available today can hope to promise more than 256 bits of security”. So it might be questionable to pass size > 32 to this method.

Random.urandom(8)  #=> "\x78\x41\xBA\xAF\x7D\xEA\xD8\xEA"

Basically the same as ::new. However, if class Thread is subclassed, then calling start in that subclass will not invoke the subclass’s initialize method.

Returns the currently executing thread.

Thread.current   #=> #<Thread:0x401bdf4c run>

Raises an exception from the given thread. The caller does not have to be thr. See Kernel#raise for more information.

Thread.abort_on_exception = true
a = Thread.new { sleep(200) }
a.raise("Gotcha")

This will produce:

prog.rb:3: Gotcha (RuntimeError)
 from prog.rb:2:in `initialize'
 from prog.rb:2:in `new'
 from prog.rb:2

Returns the current backtrace of the target thread.

A convenience method for TracePoint.new that activates the trace automatically.

trace = TracePoint.trace(:call) { |tp| [tp.lineno, tp.event] }
#=> #<TracePoint:enabled>

trace.enabled?  #=> true

Raises an exception; see Exceptions.

Argument exception sets the class of the new exception; it should be class Exception or one of its subclasses (most commonly, RuntimeError or StandardError), or an instance of one of those classes:

begin
  raise(StandardError)
rescue => x
  p x.class
end
# => StandardError

Argument message sets the stored message in the new exception, which may be retrieved by method Exception#message; the message must be a string-convertible object or nil:

begin
  raise(StandardError, 'Boom')
rescue => x
  p x.message
end
# => "Boom"

If argument message is not given, the message is the exception class name.

See Exceptions.

Argument backtrace might be used to modify the backtrace of the new exception, as reported by Exception#backtrace and Exception#backtrace_locations; the backtrace must be an array of Thread::Backtrace::Location, an array of strings, a single string, or nil.

Using the array of Thread::Backtrace::Location instances is the most consistent option and should be preferred when possible. The necessary value might be obtained from caller_locations, or copied from Exception#backtrace_locations of another error:

begin
  do_some_work()
rescue ZeroDivisionError => ex
  raise(LogicalError, "You have an error in your math", ex.backtrace_locations)
end

The ways, both Exception#backtrace and Exception#backtrace_locations of the raised error are set to the same backtrace.

When the desired stack of locations is not available and should be constructed from scratch, an array of strings or a singular string can be used. In this case, only Exception#backtrace is set:

begin
  raise(StandardError, 'Boom', %w[dsl.rb:3 framework.rb:1])
rescue => ex
  p ex.backtrace
  # => ["dsl.rb:3", "framework.rb:1"]
  p ex.backtrace_locations
  # => nil
end

If argument backtrace is not given, the backtrace is set according to an array of Thread::Backtrace::Location objects, as derived from the call stack.

See Exceptions.

Keyword argument cause sets the stored cause in the new exception, which may be retrieved by method Exception#cause; the cause must be an exception object (Exception or one of its subclasses), or nil:

begin
  raise(StandardError, cause: RuntimeError.new)
rescue => x
  p x.cause
end
# => #<RuntimeError: RuntimeError>

If keyword argument cause is not given, the cause is the value of $!.

See Exceptions.

In the alternate calling sequence, where argument exception not given, raises a new exception of the class given by $!, or of class RuntimeError if $! is nil:

begin
  raise
rescue => x
  p x
end
# => RuntimeError

With argument exception not given, argument message and keyword argument cause may be given, but argument backtrace may not be given.

Seeds the system pseudo-random number generator, with number. The previous seed value is returned.

If number is omitted, seeds the generator using a source of entropy provided by the operating system, if available (/dev/urandom on Unix systems or the RSA cryptographic provider on Windows), which is then combined with the time, the process id, and a sequence number.

srand may be used to ensure repeatable sequences of pseudo-random numbers between different runs of the program. By setting the seed to a known value, programs can be made deterministic during testing.

srand 1234               # => 268519324636777531569100071560086917274
[ rand, rand ]           # => [0.1915194503788923, 0.6221087710398319]
[ rand(10), rand(1000) ] # => [4, 664]
srand 1234               # => 1234
[ rand, rand ]           # => [0.1915194503788923, 0.6221087710398319]

If called without an argument, or if max.to_i.abs == 0, rand returns a pseudo-random floating point number between 0.0 and 1.0, including 0.0 and excluding 1.0.

rand        #=> 0.2725926052826416

When max.abs is greater than or equal to 1, rand returns a pseudo-random integer greater than or equal to 0 and less than max.to_i.abs.

rand(100)   #=> 12

When max is a Range, rand returns a random number where range.member?(number) == true.

Negative or floating point values for max are allowed, but may give surprising results.

rand(-100) # => 87
rand(-0.5) # => 0.8130921818028143
rand(1.9)  # equivalent to rand(1), which is always 0

Kernel.srand may be used to ensure that sequences of random numbers are reproducible between different runs of a program.

See also Random.rand.

Returns x/y or arg as a Rational.

Rational(2, 3)   #=> (2/3)
Rational(5)      #=> (5/1)
Rational(0.5)    #=> (1/2)
Rational(0.3)    #=> (5404319552844595/18014398509481984)

Rational("2/3")  #=> (2/3)
Rational("0.3")  #=> (3/10)

Rational("10 cents")  #=> ArgumentError
Rational(nil)         #=> TypeError
Rational(1, nil)      #=> TypeError

Rational("10 cents", exception: false)  #=> nil

Syntax of the string form:

string form = extra spaces , rational , extra spaces ;
rational = [ sign ] , unsigned rational ;
unsigned rational = numerator | numerator , "/" , denominator ;
numerator = integer part | fractional part | integer part , fractional part ;
denominator = digits ;
integer part = digits ;
fractional part = "." , digits , [ ( "e" | "E" ) , [ sign ] , digits ] ;
sign = "-" | "+" ;
digits = digit , { digit | "_" , digit } ;
digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" ;
extra spaces = ? \s* ? ;

See also String#to_r.

Specifies the handling of signals. The first parameter is a signal name (a string such as “SIGALRM”, “SIGUSR1”, and so on) or a signal number. The characters “SIG” may be omitted from the signal name. The command or block specifies code to be run when the signal is raised. If the command is the string “IGNORE” or “SIG_IGN”, the signal will be ignored. If the command is “DEFAULT” or “SIG_DFL”, the Ruby’s default handler will be invoked. If the command is “EXIT”, the script will be terminated by the signal. If the command is “SYSTEM_DEFAULT”, the operating system’s default handler will be invoked. Otherwise, the given command or block will be run. The special signal name “EXIT” or signal number zero will be invoked just prior to program termination. trap returns the previous handler for the given signal.

Signal.trap(0, proc { puts "Terminating: #{$$}" })
Signal.trap("CLD")  { puts "Child died" }
fork && Process.wait

produces:

Terminating: 27461
Child died
Terminating: 27460

Deprecated. Use block_given? instead.

If warnings have been disabled (for example with the -W0 flag), does nothing. Otherwise, converts each of the messages to strings, appends a newline character to the string if the string does not end in a newline, and calls Warning.warn with the string.

warn("warning 1", "warning 2")

produces:

warning 1
warning 2

If the uplevel keyword argument is given, the string will be prepended with information for the given caller frame in the same format used by the rb_warn C function.

# In baz.rb
def foo
  warn("invalid call to foo", uplevel: 1)
end

def bar
  foo
end

bar

produces:

baz.rb:6: warning: invalid call to foo

If category keyword argument is given, passes the category to Warning.warn. The category given must be one of the following categories:

:deprecated

Used for warning for deprecated functionality that may be removed in the future.

:experimental

Used for experimental features that may change in future releases.

:performance

Used for warning about APIs or pattern that have negative performance impact

With a block given, returns an array of two arrays:

Examples:

p = (1..4).partition {|i| i.even? }
p # => [[2, 4], [1, 3]]
p = ('a'..'d').partition {|c| c < 'c' }
p # => [["a", "b"], ["c", "d"]]
h = {foo: 0, bar: 1, baz: 2, bat: 3}
p = h.partition {|key, value| key.start_with?('b') }
p # => [[[:bar, 1], [:baz, 2], [:bat, 3]], [[:foo, 0]]]
p = h.partition {|key, value| value < 2 }
p # => [[[:foo, 0], [:bar, 1]], [[:baz, 2], [:bat, 3]]]

With no block given, returns an Enumerator.

Related: Enumerable#group_by.

Writes warning message msg to $stderr. This method is called by Ruby for all emitted warnings. A category may be included with the warning.

See the documentation of the Warning module for how to customize this.

Enables the coverage measurement. See the documentation of Coverage class in detail. This is equivalent to Coverage.setup and Coverage.resume.

Returns the memory address of the Ruby object stored at val

Example:

x = Object.new
# => #<Object:0x0000000107c7d870>
Fiddle.dlwrap(x)
# => 4425504880

In the case val is not a heap allocated object, this method will return the tagged pointer value.

Example:

Fiddle.dlwrap(123)
# => 247

Returns the Ruby object stored at the memory address addr

Example:

x = Object.new
# => #<Object:0x0000000107c7d870>
Fiddle.dlwrap(x)
# => 4425504880
Fiddle.dlunwrap(_)
# => #<Object:0x0000000107c7d870>

Returns the Ruby objects created by parsing the given source.

Argument source contains the String to be parsed.

Argument opts, if given, contains a Hash of options for the parsing. See Parsing Options.


When source is a JSON array, returns a Ruby Array:

source = '["foo", 1.0, true, false, null]'
ruby = JSON.parse(source)
ruby # => ["foo", 1.0, true, false, nil]
ruby.class # => Array

When source is a JSON object, returns a Ruby Hash:

source = '{"a": "foo", "b": 1.0, "c": true, "d": false, "e": null}'
ruby = JSON.parse(source)
ruby # => {"a"=>"foo", "b"=>1.0, "c"=>true, "d"=>false, "e"=>nil}
ruby.class # => Hash

For examples of parsing for all JSON data types, see Parsing JSON.

Parses nested JSON objects:

source = <<~JSON
  {
  "name": "Dave",
    "age" :40,
    "hats": [
      "Cattleman's",
      "Panama",
      "Tophat"
    ]
  }
JSON
ruby = JSON.parse(source)
ruby # => {"name"=>"Dave", "age"=>40, "hats"=>["Cattleman's", "Panama", "Tophat"]}

Raises an exception if source is not valid JSON:

# Raises JSON::ParserError (783: unexpected token at ''):
JSON.parse('')

Calls

parse(source, opts)

with source and possibly modified opts.

Differences from JSON.parse:

Returns a String containing the generated JSON data.

See also JSON.fast_generate, JSON.pretty_generate.

Argument obj is the Ruby object to be converted to JSON.

Argument opts, if given, contains a Hash of options for the generation. See Generating Options.


When obj is an Array, returns a String containing a JSON array:

obj = ["foo", 1.0, true, false, nil]
json = JSON.generate(obj)
json # => '["foo",1.0,true,false,null]'

When obj is a Hash, returns a String containing a JSON object:

obj = {foo: 0, bar: 's', baz: :bat}
json = JSON.generate(obj)
json # => '{"foo":0,"bar":"s","baz":"bat"}'

For examples of generating from other Ruby objects, see Generating JSON from Other Objects.


Raises an exception if any formatting option is not a String.

Raises an exception if obj contains circular references:

a = []; b = []; a.push(b); b.push(a)
# Raises JSON::NestingError (nesting of 100 is too deep):
JSON.generate(a)

See any remaining errors held in queue.

Any errors you see here are probably due to a bug in Ruby’s OpenSSL implementation.

Search took: 5ms  ·  Total Results: 2478