Equivalent to $stdout.print(*objects)
, this method is the straightforward way to write to $stdout
.
Writes the given objects to $stdout
; returns nil
. Appends the output record separator $OUTPUT_RECORD_SEPARATOR
$\
), if it is not nil
.
With argument objects
given, for each object:
Converts via its method to_s
if not a string.
Writes to stdout
.
If not the last object, writes the output field separator $OUTPUT_FIELD_SEPARATOR
($,
if it is not nil
.
With default separators:
objects = [0, 0.0, Rational(0, 1), Complex(0, 0), :zero, 'zero'] $OUTPUT_RECORD_SEPARATOR $OUTPUT_FIELD_SEPARATOR print(*objects)
Output:
nil nil 00.00/10+0izerozero
With specified separators:
$OUTPUT_RECORD_SEPARATOR = "\n" $OUTPUT_FIELD_SEPARATOR = ',' print(*objects)
Output:
0,0.0,0/1,0+0i,zero,zero
With no argument given, writes the content of $_
(which is usually the most recent user input):
gets # Sets $_ to the most recent user input. print # Prints $_.
Equivalent to method Kernel#gets
, except that it raises an exception if called at end-of-stream:
$ cat t.txt | ruby -e "p readlines; readline" ["First line\n", "Second line\n", "\n", "Fourth line\n", "Fifth line\n"] in `readline': end of file reached (EOFError)
Optional keyword argument chomp
specifies whether line separators are to be omitted.
Returns an array containing the lines returned by calling Kernel#gets
until the end-of-stream is reached; (see Line IO).
With only string argument sep
given, returns the remaining lines as determined by line separator sep
, or nil
if none; see Line Separator:
# Default separator. $ cat t.txt | ruby -e "p readlines" ["First line\n", "Second line\n", "\n", "Fourth line\n", "Fifth line\n"] # Specified separator. $ cat t.txt | ruby -e "p readlines 'li'" ["First li", "ne\nSecond li", "ne\n\nFourth li", "ne\nFifth li", "ne\n"] # Get-all separator. $ cat t.txt | ruby -e "p readlines nil" ["First line\nSecond line\n\nFourth line\nFifth line\n"] # Get-paragraph separator. $ cat t.txt | ruby -e "p readlines ''" ["First line\nSecond line\n\n", "Fourth line\nFifth line\n"]
With only integer argument limit
given, limits the number of bytes in the line; see Line Limit:
$cat t.txt | ruby -e "p readlines 10" ["First line", "\n", "Second lin", "e\n", "\n", "Fourth lin", "e\n", "Fifth line", "\n"] $cat t.txt | ruby -e "p readlines 11" ["First line\n", "Second line", "\n", "\n", "Fourth line", "\n", "Fifth line\n"] $cat t.txt | ruby -e "p readlines 12" ["First line\n", "Second line\n", "\n", "Fourth line\n", "Fifth line\n"]
With arguments sep
and limit
given, combines the two behaviors; see Line Separator and Line Limit.
Optional keyword argument chomp
specifies whether line separators are to be omitted:
$ cat t.txt | ruby -e "p readlines(chomp: true)" ["First line", "Second line", "", "Fourth line", "Fifth line"]
Optional keyword arguments enc_opts
specify encoding options; see Encoding options.
Returns the string resulting from formatting objects
into format_string
.
For details on format_string
, see Format Specifications.
Kernel#format
is an alias for Kernel#sprintf
.
Returns the string resulting from formatting objects
into format_string
.
For details on format_string
, see Format Specifications.
Kernel#format
is an alias for Kernel#sprintf
.
Returns an integer converted from object
.
Tries to convert object
to an integer using to_int
first and to_i
second; see below for exceptions.
With a non-zero base
, object
must be a string or convertible to a string.
With integer argument object
given, returns object
:
Integer(1) # => 1 Integer(-1) # => -1
With floating-point argument object
given, returns object
truncated to an intger:
Integer(1.9) # => 1 # Rounds toward zero. Integer(-1.9) # => -1 # Rounds toward zero.
With string argument object
and zero base
given, returns object
converted to an integer in base 10:
Integer('100') # => 100 Integer('-100') # => -100
With base
zero, string object
may contain leading characters to specify the actual base (radix indicator):
Integer('0100') # => 64 # Leading '0' specifies base 8. Integer('0b100') # => 4 # Leading '0b', specifies base 2. Integer('0x100') # => 256 # Leading '0x' specifies base 16.
With a positive base
(in range 2..36) given, returns object
converted to an integer in the given base:
Integer('100', 2) # => 4 Integer('100', 8) # => 64 Integer('-100', 16) # => -256
With a negative base
(in range -36..-2) given, returns object
converted to an integer in the radix indicator if exists or -base
:
Integer('0x100', -2) # => 256 Integer('100', -2) # => 4 Integer('0b100', -8) # => 4 Integer('100', -8) # => 64 Integer('0o100', -10) # => 64 Integer('100', -10) # => 100
base
-1 is equal the -10 case.
When converting strings, surrounding whitespace and embedded underscores are allowed and ignored:
Integer(' 100 ') # => 100 Integer('-1_0_0', 16) # => -256
Examples with object
of various other classes:
Integer(Rational(9, 10)) # => 0 # Rounds toward zero. Integer(Complex(2, 0)) # => 2 # Imaginary part must be zero. Integer(Time.now) # => 1650974042
With optional keyword argument exception
given as true
(the default):
Raises TypeError
if object
does not respond to to_int
or to_i
.
Raises TypeError
if object
is nil
.
Raise ArgumentError
if object
is an invalid string.
With exception
given as false
, an exception of any kind is suppressed and nil
is returned.
Returns a string converted from object
.
Tries to convert object
to a string using to_str
first and to_s
second:
String([0, 1, 2]) # => "[0, 1, 2]" String(0..5) # => "0..5" String({foo: 0, bar: 1}) # => "{:foo=>0, :bar=>1}"
Raises TypeError
if object
cannot be converted to a string.
Returns the first element for which the block returns a truthy value.
With a block given, calls the block with successive elements of the collection; returns the first element for which the block returns a truthy value:
(0..9).find {|element| element > 2} # => 3
If no such element is found, calls if_none_proc
and returns its return value.
(0..9).find(proc {false}) {|element| element > 12} # => false {foo: 0, bar: 1, baz: 2}.find {|key, value| key.start_with?('b') } # => [:bar, 1] {foo: 0, bar: 1, baz: 2}.find(proc {[]}) {|key, value| key.start_with?('c') } # => []
With no block given, returns an Enumerator.
Returns an array of objects returned by the block.
With a block given, calls the block with successive elements; returns an array of the objects returned by the block:
(0..4).map {|i| i*i } # => [0, 1, 4, 9, 16] {foo: 0, bar: 1, baz: 2}.map {|key, value| value*2} # => [0, 2, 4]
With no block given, returns an Enumerator.
Returns an object formed from operands via either:
A method named by symbol
.
A block to which each operand is passed.
With method-name argument symbol
, combines operands using the method:
# Sum, without initial_operand. (1..4).inject(:+) # => 10 # Sum, with initial_operand. (1..4).inject(10, :+) # => 20
With a block, passes each operand to the block:
# Sum of squares, without initial_operand. (1..4).inject {|sum, n| sum + n*n } # => 30 # Sum of squares, with initial_operand. (1..4).inject(2) {|sum, n| sum + n*n } # => 32
Operands
If argument initial_operand
is not given, the operands for inject
are simply the elements of self
. Example calls and their operands:
(1..4).inject(:+)
[1, 2, 3, 4]
.
(1...4).inject(:+)
[1, 2, 3]
.
('a'..'d').inject(:+)
['a', 'b', 'c', 'd']
.
('a'...'d').inject(:+)
['a', 'b', 'c']
.
Examples with first operand (which is self.first
) of various types:
# Integer. (1..4).inject(:+) # => 10 # Float. [1.0, 2, 3, 4].inject(:+) # => 10.0 # Character. ('a'..'d').inject(:+) # => "abcd" # Complex. [Complex(1, 2), 3, 4].inject(:+) # => (8+2i)
If argument initial_operand
is given, the operands for inject
are that value plus the elements of self
. Example calls their operands:
(1..4).inject(10, :+)
[10, 1, 2, 3, 4]
.
(1...4).inject(10, :+)
[10, 1, 2, 3]
.
('a'..'d').inject('e', :+)
['e', 'a', 'b', 'c', 'd']
.
('a'...'d').inject('e', :+)
['e', 'a', 'b', 'c']
.
Examples with initial_operand
of various types:
# Integer. (1..4).inject(2, :+) # => 12 # Float. (1..4).inject(2.0, :+) # => 12.0 # String. ('a'..'d').inject('foo', :+) # => "fooabcd" # Array. %w[a b c].inject(['x'], :push) # => ["x", "a", "b", "c"] # Complex. (1..4).inject(Complex(2, 2), :+) # => (12+2i)
Combination by Given Method
If the method-name argument symbol
is given, the operands are combined by that method:
The first and second operands are combined.
That result is combined with the third operand.
That result is combined with the fourth operand.
And so on.
The return value from inject
is the result of the last combination.
This call to inject
computes the sum of the operands:
(1..4).inject(:+) # => 10
Examples with various methods:
# Integer addition. (1..4).inject(:+) # => 10 # Integer multiplication. (1..4).inject(:*) # => 24 # Character range concatenation. ('a'..'d').inject('', :+) # => "abcd" # String array concatenation. %w[foo bar baz].inject('', :+) # => "foobarbaz" # Hash update. h = [{foo: 0, bar: 1}, {baz: 2}, {bat: 3}].inject(:update) h # => {:foo=>0, :bar=>1, :baz=>2, :bat=>3} # Hash conversion to nested arrays. h = {foo: 0, bar: 1}.inject([], :push) h # => [[:foo, 0], [:bar, 1]]
Combination by Given Block
If a block is given, the operands are passed to the block:
The first call passes the first and second operands.
The second call passes the result of the first call, along with the third operand.
The third call passes the result of the second call, along with the fourth operand.
And so on.
The return value from inject
is the return value from the last block call.
This call to inject
gives a block that writes the memo and element, and also sums the elements:
(1..4).inject do |memo, element| p "Memo: #{memo}; element: #{element}" memo + element end # => 10
Output:
"Memo: 1; element: 2" "Memo: 3; element: 3" "Memo: 6; element: 4"
Enumerable#reduce
is an alias for Enumerable#inject
.
Returns whether for any element object == element
:
(1..4).include?(2) # => true (1..4).include?(5) # => false (1..4).include?('2') # => false %w[a b c d].include?('b') # => true %w[a b c d].include?('2') # => false {foo: 0, bar: 1, baz: 2}.include?(:foo) # => true {foo: 0, bar: 1, baz: 2}.include?('foo') # => false {foo: 0, bar: 1, baz: 2}.include?(0) # => false
Enumerable#member?
is an alias for Enumerable#include?
.
Returns an enumerator object generated from this enumerator and given enumerables.
e = (1..3).chain([4, 5]) e.to_a #=> [1, 2, 3, 4, 5]
Computes the sine of decimal
to the specified number of digits of precision, numeric
.
If decimal
is Infinity or NaN, returns NaN.
BigMath.sin(BigMath.PI(5)/4, 5).to_s #=> "0.70710678118654752440082036563292800375e0"
Returns true if coverage stats are currently being collected (after Coverage.start
call, but before Coverage.result
call)
Returns the short user name of the currently logged in user. Unfortunately, it is often rather easy to fool ::getlogin
.
Avoid ::getlogin
for security-related purposes.
If ::getlogin
fails, try ::getpwuid
.
See the unix manpage for getpwuid(3)
for more detail.
e.g.
Etc.getlogin -> 'guest'
Allocate size
bytes of memory and return the integer memory address for the allocated memory.
Shows the prompt
and reads the inputted line with line editing. The inputted line is added to the history if add_hist
is true.
Returns nil when the inputted line is empty and user inputs EOF (Presses ^D on UNIX).
Raises IOError
exception if one of below conditions are satisfied.
stdin was closed.
stdout was closed.
This method supports thread. Switches the thread context when waits inputting line.
Supports line edit when inputs line. Provides VI and Emacs editing mode. Default is Emacs editing mode.
NOTE: Terminates ruby interpreter and does not return the terminal status after user pressed ā^Cā when wait inputting line. Give 3 examples that avoid it.
Catches the Interrupt
exception by pressed ^C after returns terminal status:
require "readline" stty_save = `stty -g`.chomp begin while buf = Readline.readline p buf end rescue Interrupt system("stty", stty_save) exit end end end
Catches the INT signal by pressed ^C after returns terminal status:
require "readline" stty_save = `stty -g`.chomp trap("INT") { system "stty", stty_save; exit } while buf = Readline.readline p buf end
Ignores pressing ^C:
require "readline" trap("INT", "SIG_IGN") while buf = Readline.readline p buf end
Can make as follows with Readline::HISTORY
constant. It does not record to the history if the inputted line is empty or the same it as last one.
require "readline" while buf = Readline.readline("> ", true) # p Readline::HISTORY.to_a Readline::HISTORY.pop if /^\s*$/ =~ buf begin if Readline::HISTORY[Readline::HISTORY.length-2] == buf Readline::HISTORY.pop end rescue IndexError end # p Readline::HISTORY.to_a print "-> ", buf, "\n" end
Specifies a File
object input
that is input stream for Readline.readline
method.
Returns the index of the current cursor position in Readline.line_buffer
.
The index in Readline.line_buffer
which matches the start of input-string passed to completion_proc
is computed by subtracting the length of input-string from Readline.point
.
start = (the length of input-string) - Readline.point
Raises NotImplementedError
if the using readline library does not support.
Set
the index of the current cursor position in Readline.line_buffer
.
Raises NotImplementedError
if the using readline library does not support.
See Readline.point
.
Returns the log priority mask in effect. The mask is not reset by opening or closing syslog.
Sets the log priority mask. A method LOG_UPTO is defined to make it easier to set mask values. Example:
Syslog.mask = Syslog::LOG_UPTO(Syslog::LOG_ERR)
Alternatively, specific priorities can be selected and added together using binary OR. Example:
Syslog.mask = Syslog::LOG_MASK(Syslog::LOG_ERR) | Syslog::LOG_MASK(Syslog::LOG_CRIT)
The priority mask persists through calls to open() and close().
Returns an inspect() string summarizing the object state.
Returns self, for backward compatibility.
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