Results for: "Data"

Looks up the first IP address for name.

Looks up all IP address for name.

Returns the full path name of the temporary file. This will be nil if unlink has been called.

Creates a file in the underlying file system; returns a new File object based on that file.

With no block given and no arguments, creates and returns file whose:

With no block, the file is not removed automatically, and so should be explicitly removed.

Example:

f = Tempfile.create     # => #<File:/tmp/20220505-9795-17ky6f6>
f.class                 # => File
f.path                  # => "/tmp/20220505-9795-17ky6f6"
f.stat.mode.to_s(8)     # => "100600"
File.exist?(f.path)     # => true
File.unlink(f.path)
File.exist?(f.path)     # => false

Argument basename, if given, may be one of:

With arguments basename and tmpdir, the file is created in directory tmpdir:

Tempfile.create('foo', '.') # => #<File:./foo20220505-9795-1emu6g8>

Keyword arguments mode and options are passed directly to method File.open:

With a block given, creates the file as above, passes it to the block, and returns the block’s value; before the return, the file object is closed and the underlying file is removed:

Tempfile.create {|file| file.path } # => "/tmp/20220505-9795-rkists"

Related: Tempfile.new.

Returns true if a Proc object is lambda. false if non-lambda.

The lambda-ness affects argument handling and the behavior of return and break.

A Proc object generated by proc ignores extra arguments.

proc {|a,b| [a,b] }.call(1,2,3)    #=> [1,2]

It provides nil for missing arguments.

proc {|a,b| [a,b] }.call(1)        #=> [1,nil]

It expands a single array argument.

proc {|a,b| [a,b] }.call([1,2])    #=> [1,2]

A Proc object generated by lambda doesn’t have such tricks.

lambda {|a,b| [a,b] }.call(1,2,3)  #=> ArgumentError
lambda {|a,b| [a,b] }.call(1)      #=> ArgumentError
lambda {|a,b| [a,b] }.call([1,2])  #=> ArgumentError

Proc#lambda? is a predicate for the tricks. It returns true if no tricks apply.

lambda {}.lambda?            #=> true
proc {}.lambda?              #=> false

Proc.new is the same as proc.

Proc.new {}.lambda?          #=> false

lambda, proc and Proc.new preserve the tricks of a Proc object given by & argument.

lambda(&lambda {}).lambda?   #=> true
proc(&lambda {}).lambda?     #=> true
Proc.new(&lambda {}).lambda? #=> true

lambda(&proc {}).lambda?     #=> false
proc(&proc {}).lambda?       #=> false
Proc.new(&proc {}).lambda?   #=> false

A Proc object generated by & argument has the tricks

def n(&b) b.lambda? end
n {}                         #=> false

The & argument preserves the tricks if a Proc object is given by & argument.

n(&lambda {})                #=> true
n(&proc {})                  #=> false
n(&Proc.new {})              #=> false

A Proc object converted from a method has no tricks.

def m() end
method(:m).to_proc.lambda?   #=> true

n(&method(:m))               #=> true
n(&method(:m).to_proc)       #=> true

define_method is treated the same as method definition. The defined method has no tricks.

class C
  define_method(:d) {}
end
C.new.d(1,2)       #=> ArgumentError
C.new.method(:d).to_proc.lambda?   #=> true

define_method always defines a method without the tricks, even if a non-lambda Proc object is given. This is the only exception for which the tricks are not preserved.

class C
  define_method(:e, &proc {})
end
C.new.e(1,2)       #=> ArgumentError
C.new.method(:e).to_proc.lambda?   #=> true

This exception ensures that methods never have tricks and makes it easy to have wrappers to define methods that behave as usual.

class C
  def self.def2(name, &body)
    define_method(name, &body)
  end

  def2(:f) {}
end
C.new.f(1,2)       #=> ArgumentError

The wrapper def2 defines a method which has no tricks.

Get a message from the ractor’s outgoing port, which was put there by Ractor.yield or at ractor’s termination.

r = Ractor.new do
  Ractor.yield 'explicit yield'
  'last value'
end
puts r.take #=> 'explicit yield'
puts r.take #=> 'last value'
puts r.take # Ractor::ClosedError (The outgoing-port is already closed)

The fact that the last value is also sent to the outgoing port means that take can be used as an analog of Thread#join (“just wait until ractor finishes”). However, it will raise if somebody has already consumed that message.

If the outgoing port was closed with close_outgoing, the method will raise Ractor::ClosedError.

r = Ractor.new do
  sleep(500)
  Ractor.yield 'Hello from ractor'
end
r.close_outgoing
r.take
# Ractor::ClosedError (The outgoing-port is already closed)
# The error would be raised immediately, not when ractor will try to receive

If an uncaught exception is raised in the Ractor, it is propagated by take as a Ractor::RemoteError.

r = Ractor.new {raise "Something weird happened"}

begin
  r.take
rescue => e
  p e              #  => #<Ractor::RemoteError: thrown by remote Ractor.>
  p e.ractor == r  # => true
  p e.cause        # => #<RuntimeError: Something weird happened>
end

Ractor::ClosedError is a descendant of StopIteration, so the termination of the ractor will break out of any loops that receive this message without propagating the error:

r = Ractor.new do
  3.times {|i| Ractor.yield "message #{i}"}
  "finishing"
end

loop {puts "Received: " + r.take}
puts "Continue successfully"

This will print:

Received: message 0
Received: message 1
Received: message 2
Received: finishing
Continue successfully

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.

Terminates thr and schedules another thread to be run, returning the terminated Thread. If this is the main thread, or the last thread, exits the process.

Path of the file being run

Return the tag object which was called for.

Creates a new Pathname object from the given string, path, and returns pathname object.

In order to use this constructor, you must first require the Pathname standard library extension.

require 'pathname'
Pathname("/home/zzak")
#=> #<Pathname:/home/zzak>

See also Pathname::new for more information.

Yields self to the block, and then returns self. The primary purpose of this method is to “tap into” a method chain, in order to perform operations on intermediate results within the chain.

(1..10)                  .tap {|x| puts "original: #{x}" }
  .to_a                  .tap {|x| puts "array:    #{x}" }
  .select {|x| x.even? } .tap {|x| puts "evens:    #{x}" }
  .map {|x| x*x }        .tap {|x| puts "squares:  #{x}" }

Returns arg converted to a float. Numeric types are converted directly, and with exception to String and nil the rest are converted using arg.to_f. Converting a String with invalid characters will result in a ArgumentError. Converting nil generates a TypeError. Exceptions can be suppressed by passing exception: false.

Float(1)                 #=> 1.0
Float("123.456")         #=> 123.456
Float("123.0_badstring") #=> ArgumentError: invalid value for Float(): "123.0_badstring"
Float(nil)               #=> TypeError: can't convert nil into Float
Float("123.0_badstring", exception: false)  #=> nil

Returns the string resulting from formatting objects into format_string.

For details on format_string, see Format Specifications.

Equivalent to Proc.new, except the resulting Proc objects check the number of parameters passed when called.

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.

Deprecated. Use block_given? instead.

catch executes its block. If throw is not called, the block executes normally, and catch returns the value of the last expression evaluated.

catch(1) { 123 }            # => 123

If throw(tag2, val) is called, Ruby searches up its stack for a catch block whose tag has the same object_id as tag2. When found, the block stops executing and returns val (or nil if no second argument was given to throw).

catch(1) { throw(1, 456) }  # => 456
catch(1) { throw(1) }       # => nil

When tag is passed as the first argument, catch yields it as the parameter of the block.

catch(1) {|x| x + 2 }       # => 3

When no tag is given, catch yields a new unique object (as from Object.new) as the block parameter. This object can then be used as the argument to throw, and will match the correct catch block.

catch do |obj_A|
  catch do |obj_B|
    throw(obj_B, 123)
    puts "This puts is not reached"
  end

  puts "This puts is displayed"
  456
end

# => 456

catch do |obj_A|
  catch do |obj_B|
    throw(obj_A, 123)
    puts "This puts is still not reached"
  end

  puts "Now this puts is also not reached"
  456
end

# => 123

Returns a hash containing the counts of equal elements:

With no argument:

%w[a b c b c a c b].tally # => {"a"=>2, "b"=>3, "c"=>3}

With a hash argument, that hash is used for the tally (instead of a new hash), and is returned; this may be useful for accumulating tallies across multiple enumerables:

hash = {}
hash = %w[a c d b c a].tally(hash)
hash # => {"a"=>2, "c"=>2, "d"=>1, "b"=>1}
hash = %w[b a z].tally(hash)
hash # => {"a"=>3, "c"=>2, "d"=>1, "b"=>2, "z"=>1}
hash = %w[b a m].tally(hash)
hash # => {"a"=>4, "c"=>2, "d"=>1, "b"=>3, "z"=>1, "m"=> 1}

For non-negative integer n, returns the first n elements:

r = (1..4)
r.take(2) # => [1, 2]
r.take(0) # => []

h = {foo: 0, bar: 1, baz: 2, bat: 3}
h.take(2) # => [[:foo, 0], [:bar, 1]]

Returns a list of the supported category symbols.

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

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)

Compresses the given string. Valid values of level are Zlib::NO_COMPRESSION, Zlib::BEST_SPEED, Zlib::BEST_COMPRESSION, Zlib::DEFAULT_COMPRESSION, or an integer from 0 to 9.

This method is almost equivalent to the following code:

def deflate(string, level)
  z = Zlib::Deflate.new(level)
  dst = z.deflate(string, Zlib::FINISH)
  z.close
  dst
end

See also Zlib.inflate

Decompresses string. Raises a Zlib::NeedDict exception if a preset dictionary is needed for decompression.

This method is almost equivalent to the following code:

def inflate(string)
  zstream = Zlib::Inflate.new
  buf = zstream.inflate(string)
  zstream.finish
  zstream.close
  buf
end

See also Zlib.deflate

Search took: 6ms  ·  Total Results: 2131