These are valid (but not recommended):
"Safe level is #$SAFE" # => Safe level is 0
class Test1
@@etc = 1
def test
@eg = 2
"@@etc = #@@etc, @eg = #@eg"
end
end
Test1.new.test # => @@etc = 1, @eg = 2
Use String#scan for repeating patterns inside strings (p. 90)
length = '2:58'
mins, secs = length.scan(/\d+/) # => 2, 58
class PowerOfTwo
attr_reader :value
def initialize(value)
@value = value
end
def <=>(other)
@value <=> other.value
end
def succ
# Modified for readability: @value + @value -> @value * 2
self.class.new(@value * 2)
end
def to_s
@value.to_s
end
end
p1 = PowerOfTwo.new(4)
p2 = PowerOfTwo.new(32)
(p1..p2).to_a # => [#<PowerOfTwo:0x007fc6233ee9c8 @value=4>, <...8>, <...16>, <...32>]
Poor man's Markdown highlighter
while line = gets
puts highlight(line) if line =~ /^```/ ... line =~ /^```/
end
Note that there is a discussion regarding its removal in Ruby 3.
/hay/ =~ 'haystack' #=> 0
'haystack' =~ /hay/ #=> 0
s = 'cat and dog'
s.sub(/at/, 'ub') # => cub and dog
s.sub(/mat/, 'ub') # => cat and dog (no match)
s.sub!(/at/, 'ub') # => cub and dog
s.sub!(/mat/, 'ub') # => nil (no match)
Can be useful in conditionals:
if s.sub!(...)
puts 'Replaced!'
end
\h
=[0-9a-fA-F]
- Hexadecimal digit character\R
- Generic linebreak sequence, matches\n
,\r
or\r\n
(new in Ruby 2)
- Use
Object#freeze
. If you suspect that some unknown portion of code is setting a variable to a bogus value, try freezing the variable. The culprit will then be caught during the attempt to modify the variable.
One major technique makes writing Ruby code both easier and more fun. Develop your applications incrementally. Write a few lines of code, and then write tests (perhaps using Test::Unit). Write a few more lines of code, and then exercise them. One of the major benefits of a dynamically typed language is that things don’t have to be complete before you use them.