Create parser string nodes from a single prism node. The parser gem “glues” strings together when a line continuation is encountered.
@foo = 1 ^^^^^^^^ @foo, @bar = 1 ^^^^ ^^^^
Attempts to return an array, based on the given object
.
If object
is an array, returns object
.
Otherwise if object
responds to :to_ary
. calls object.to_ary
: if the return value is an array or nil
, returns that value; if not, raises TypeError
.
Otherwise returns nil
.
Related: see Methods for Creating an Array.
If object
is an Integer object, returns object
.
Integer.try_convert(1) # => 1
Otherwise if object
responds to :to_int
, calls object.to_int
and returns the result.
Integer.try_convert(1.25) # => 1
Returns nil
if object
does not respond to :to_int
Integer.try_convert([]) # => nil
Raises an exception unless object.to_int
returns an Integer object.
Attempts to convert the given object
to a string.
If object
is already a string, returns object
, unmodified.
Otherwise if object
responds to :to_str
, calls object.to_str
and returns the result.
Returns nil
if object
does not respond to :to_str
.
Raises an exception unless object.to_str
returns a string.
Returns an array of the grapheme clusters in self
(see Unicode Grapheme Cluster Boundaries):
s = "\u0061\u0308-pqr-\u0062\u0308-xyz-\u0063\u0308" # => "ä-pqr-b̈-xyz-c̈" s.grapheme_clusters # => ["ä", "-", "p", "q", "r", "-", "b̈", "-", "x", "y", "z", "-", "c̈"]
Returns whether self
starts with any of the given string_or_regexp
.
Matches patterns against the beginning of self
. For each given string_or_regexp
, the pattern is:
string_or_regexp
itself, if it is a Regexp
.
Regexp.quote(string_or_regexp)
, if string_or_regexp
is a string.
Returns true
if any pattern matches the beginning, false
otherwise:
'hello'.start_with?('hell') # => true 'hello'.start_with?(/H/i) # => true 'hello'.start_with?('heaven', 'hell') # => true 'hello'.start_with?('heaven', 'paradise') # => false 'тест'.start_with?('т') # => true 'こんにちは'.start_with?('こ') # => true
Related: String#end_with?
.
Like String#tr_s
, but modifies self
in place. Returns self
if any changes were made, nil
otherwise.
Related: String#squeeze!
.
Like backtrace
, but returns each line of the execution stack as a Thread::Backtrace::Location
. Accepts the same arguments as backtrace
.
f = Fiber.new { Fiber.yield } f.resume loc = f.backtrace_locations.first loc.label #=> "yield" loc.path #=> "test.rb" loc.lineno #=> 1
Returns true
if the named file is writable by the real user and group id of this process. See access(3).
Note that some OS-level security features may cause this to return true even though the file is not writable by the real user/group.
If file_name is writable by others, returns an integer representing the file permission bits of file_name. Returns nil
otherwise. The meaning of the bits is platform dependent; on Unix systems, see stat(2)
.
file_name can be an IO
object.
File.world_writable?("/tmp") #=> 511 m = File.world_writable?("/tmp") sprintf("%o", m) #=> "777"
Returns the list of available encoding names.
Encoding.name_list #=> ["US-ASCII", "ASCII-8BIT", "UTF-8", "ISO-8859-1", "Shift_JIS", "EUC-JP", "Windows-31J", "BINARY", "CP932", "eucJP"]
Returns the list of private methods accessible to obj. If the all parameter is set to false
, only those methods in the receiver will be listed.
Returns true
if obj is an instance of the given class. See also Object#kind_of?
.
class A; end class B < A; end class C < B; end b = B.new b.instance_of? A #=> false b.instance_of? B #=> true b.instance_of? C #=> false
Returns the backtrace (the list of code locations that led to the exception), as an array of Thread::Backtrace::Location
instances.
Example (assuming the code is stored in the file named t.rb
):
def division(numerator, denominator) numerator / denominator end begin division(1, 0) rescue => ex p ex.backtrace_locations # ["t.rb:2:in 'Integer#/'", "t.rb:2:in 'Object#division'", "t.rb:6:in '<main>'"] loc = ex.backtrace_locations.first p loc.class # Thread::Backtrace::Location p loc.path # "t.rb" p loc.lineno # 2 p loc.label # "Integer#/" end
The value returned by this method might be adjusted when raising (see Kernel#raise
), or during intermediate handling by set_backtrace
.
See also backtrace
that provide the same value as an array of strings. (Note though that two values might not be consistent with each other when backtraces are manually adjusted.)
See Backtraces.
Sets the backtrace value for self
; returns the given value
.
The value
might be:
an array of Thread::Backtrace::Location
;
an array of String
instances;
a single String
instance; or
nil
.
Using array of Thread::Backtrace::Location
is the most consistent option: it sets both backtrace
and backtrace_locations
. It should be preferred when possible. The suitable array of locations can be obtained from Kernel#caller_locations
, copied from another error, or just set to the adjusted result of the current error’s backtrace_locations
:
require 'json' def parse_payload(text) JSON.parse(text) # test.rb, line 4 rescue JSON::ParserError => ex ex.set_backtrace(ex.backtrace_locations[2...]) raise end parse_payload('{"wrong: "json"') # test.rb:4:in 'Object#parse_payload': unexpected token at '{"wrong: "json"' (JSON::ParserError) # # An error points to the body of parse_payload method, # hiding the parts of the backtrace related to the internals # of the "json" library # The error has both #backtace and #backtrace_locations set # consistently: begin parse_payload('{"wrong: "json"') rescue => ex p ex.backtrace # ["test.rb:4:in 'Object#parse_payload'", "test.rb:20:in '<main>'"] p ex.backtrace_locations # ["test.rb:4:in 'Object#parse_payload'", "test.rb:20:in '<main>'"] end
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 backtrace
is affected:
def parse_payload(text) JSON.parse(text) rescue JSON::ParserError => ex ex.set_backtrace(["dsl.rb:34", "framework.rb:1"]) # The error have the new value in #backtrace: p ex.backtrace # ["dsl.rb:34", "framework.rb:1"] # but the original one in #backtrace_locations p ex.backtrace_locations # [".../json/common.rb:221:in 'JSON::Ext::Parser.parse'", ...] end parse_payload('{"wrong: "json"')
Calling set_backtrace
with nil
clears up backtrace
but doesn’t affect backtrace_locations
:
def parse_payload(text) JSON.parse(text) rescue JSON::ParserError => ex ex.set_backtrace(nil) p ex.backtrace # nil p ex.backtrace_locations # [".../json/common.rb:221:in 'JSON::Ext::Parser.parse'", ...] end parse_payload('{"wrong: "json"')
On reraising of such an exception, both backtrace
and backtrace_locations
is set to the place of reraising:
def parse_payload(text) JSON.parse(text) rescue JSON::ParserError => ex ex.set_backtrace(nil) raise # test.rb, line 7 end begin parse_payload('{"wrong: "json"') rescue => ex p ex.backtrace # ["test.rb:7:in 'Object#parse_payload'", "test.rb:11:in '<main>'"] p ex.backtrace_locations # ["test.rb:7:in 'Object#parse_payload'", "test.rb:11:in '<main>'"] end
See Backtraces.
Return a list of the local variable names defined where this NameError
exception was raised.
Internal use only.
Return true if the caused method was called as private.
Invoked as a callback whenever a constant is assigned on the receiver
module Chatty def self.const_added(const_name) super puts "Added #{const_name.inspect}" end FOO = 1 end
produces:
Added :FOO
If we define a class using the class
keyword, const_added
runs before inherited
:
module M def self.const_added(const_name) super p :const_added end parent = Class.new do def self.inherited(subclass) super p :inherited end end class Child < parent end end
produces:
:const_added :inherited
Creates instance variables and corresponding methods that return the value of each instance variable. Equivalent to calling “attr
:name” on each name in turn. String
arguments are converted to symbols. Returns an array of defined method names as symbols.
Defines a named attribute for this module, where the name is symbol.id2name
, creating an instance variable (@name
) and a corresponding access method to read it. Also creates a method called name=
to set the attribute. String
arguments are converted to symbols. Returns an array of defined method names as symbols.
module Mod attr_accessor(:one, :two) #=> [:one, :one=, :two, :two=] end Mod.instance_methods.sort #=> [:one, :one=, :two, :two=]
Returns an array containing the names of the public and protected instance methods in the receiver. For a module, these are the public and protected methods; for a class, they are the instance (not singleton) methods. If the optional parameter is false
, the methods of any ancestors are not included.
module A def method1() end end class B include A def method2() end end class C < B def method3() end end A.instance_methods(false) #=> [:method1] B.instance_methods(false) #=> [:method2] B.instance_methods(true).include?(:method1) #=> true C.instance_methods(false) #=> [:method3] C.instance_methods.include?(:method2) #=> true
Note that method visibility changes in the current class, as well as aliases, are considered as methods of the current class by this method:
class C < B alias method4 method2 protected :method2 end C.instance_methods(false).sort #=> [:method2, :method3, :method4]
Checks for a constant with the given name in mod. If inherit
is set, the lookup will also search the ancestors (and Object
if mod is a Module
).
The value of the constant is returned if a definition is found, otherwise a NameError
is raised.
Math.const_get(:PI) #=> 3.14159265358979
This method will recursively look up constant names if a namespaced class name is provided. For example:
module Foo; class Bar; end end Object.const_get 'Foo::Bar'
The inherit
flag is respected on each lookup. For example:
module Foo class Bar VAL = 10 end class Baz < Bar; end end Object.const_get 'Foo::Baz::VAL' # => 10 Object.const_get 'Foo::Baz::VAL', false # => NameError
If the argument is not a valid constant name a NameError
will be raised with a warning “wrong constant name”.
Object.const_get 'foobar' #=> NameError: wrong constant name foobar