Вывести список методов объекта
require 'pp'
pp String.methods
["private_class_method", "inspect", "name", "tap",
"clone", "public_methods", "__send__", "object_id",
"method_defined?", "instance_variable_defined?",
...
Храним данные вместе с исходным кодом
puts DATA.read
__END__
I can put anything I want
after the __END__ symbol
and access it with the
DATA global. Whoa!
ARGF преобразует переданные в виде аргументов имена файлов в единый поток, с которого можно читать данные
# shell> echo "inside a.txt" > a.txt
# shell> echo "inside b.txt" > b.txt
# shell> cat a.txt b.txt
# inside a.txt
# inside b.txt
# linenum.rb
ARGF.each do |line|
puts "%3d: %s" % [ARGF.lineno, line]
end
shell> ruby linenum.rb a.txt b.txt
1: inside a.txt
2: inside b.txt
Получить колличество переданых аргументов
$ echo 'puts ARGV.length' | ruby - one two three
Напечатать сообщение и оборвать выполнение
abort("Segmentation fault")
Если session[:cart] не задан - установить значение по умолчанию
session[:cart] ||= default
Проверить есть ли элемент в массиве
if ["a", "b", "c", "d"].include?('a')
puts 'Found it in the array'
end
Found it in the array
Инкремент/декремент в руби. Само значение правда не изменяется.
1.pred #=> 0
(-1).pred #=> -2
1.next #=> 2
(-1).next #=> 0
Корректно обрабатывае нажатие CTRL-C от пользователя
trap("INT") do
puts "Correct exit";
exit
end
while true do end
Вызвать функцию по имени.
def hello name
puts "Hello, #{name}!"
end
send :hello, :waserd
Hello, waserd!
Обойти файл построчно
$ cat test.rb
i = 0
File.open('test.rb').each do |line|
i += 1
print "#{i}\t#{line}"
end
$ ruby test.rb
1 i = 0
2 File.open('test.rb').each do |line|
3 i += 1
4 print "#{i}\t#{line}"
5 end
Определяем функцию для определения функций =_+
def deff name, &block
self.class.send(:define_method, name, &block)
end
Открыв внешнюю команду на выполнение - передавать и читать с неё данные
IO.popen("pr --columns 3 -at", "r+") do |io|
(1..10).each { |i| io.puts "Line #{i}\n" }
io.close_write
puts io.readlines
end
$ ./test.rb
Line 1 Line 2 Line 3
Line 4 Line 5 Line 6
Line 7 Line 8 Line 9
Line 10
Получаем 1 символ из ввода пользователя, перехватывая нажатия Ctrl и Alt.
Содержимое test.rb
def get_char
key = ""
begin
system("stty raw -echo")
f = STDIN.getc
if (1..26) === f
key = "C-" + (f + 96).chr
elsif f == ?\e
c = STDIN.getc
if (1..26) === c
key = "C-A-" + (c + 96).chr
else
key = "A-" + c.chr
end
else
if f >= 208
key = f.chr + STDIN.getc.chr
else
key = f.chr
end
end
ensure
system("stty -raw echo")
end
key
end
while c = get_char
exit if c == "q"
puts c
end
Запускаем:
$ ruby test.rb
a
a
ф
ф
Ctrl+s
C-s
Alt+d
A-d
1
1
Ctrl+Alt+w
C-A-w
Output-buffering в ruby. Выполняем код, который печатает в stdout и возвращаем его как строку.
require "stringio"
def ob
buffer = StringIO.new
old_stdout = $stdout
$stdout = buffer
yield
$stdout = old_stdout
buffer.rewind
buffer.read
end
v = ob do
puts "hello"
end
v2 = ob do
puts "world"
end
puts v2 + v
puts(ob do
print ">"
r = ob do
print "!"
end
print "<"
print r
end)
world
hello
><!
Запустить mplayer на воспроизведение файла и передавать ему команды
IO.popen("mplayer music.mp3 2> /dev/null ", "r+") do |io|
while t = gets.chomp
io.print t
end
end
Передаём опции в функцию
require 'pp'
def foo(opts = {})
opts = {:key => :value, :key2 => :value2}.merge(opts)
end
pp foo
pp foo(:bar => :baz,
:key => :value3)
{:key=>:value, :key2=>:value2}
{:key=>:value3, :key2=>:value2, :bar=>:baz}
Игнорируем исключения в блоке кода
def ignore_exception
begin
yield
rescue Exception
end
end
ignore_exception do
puts "Ignoring Exception"
raise Exception
puts "This is Ignored"
end
puts "This is NOT ignored"
Ignoring Exception
This is NOT ignored
Получить один символ и вернуть управление программе. На stackoverflow ещё есть интересные примеры - стоит почитать первоисточник
tty_param = `stty -g`
system 'stty raw'
a = IO.read '/dev/stdin', 1
system "stty #{tty_param}"
print a
Число в объект Time
Time.at(1234567890)
=> 2009-02-14 02:31:30 +0300
heredoc синтаксис
print <<EOF
The price is #{$Price}.
EOF
print <<"EOF"; # same as above
The price is #{$Price}.
EOF
print <<`EOC` # execute commands
echo hi there
echo lo there
EOC
print <<"foo", <<"bar" # you can stack them
I said foo.
foo
I said bar.
bar
myfunc(<<"THIS", 23, <<'THAT')
Here's a line
or two.
THIS
and here's another.
THAT
if need_define_foo
eval <<-EOS # delimiters can be indented
def foo
print "foo\n"
end
EOS
end
Устанавливаем mysql соединение через ssh-туннель, авторизуясь по ключам
#!/usr/bin/env ruby
require 'rubygems'
require 'mysql2'
require 'net/ssh/gateway'
gateway = Net::SSH::Gateway.new('productionserver.ru', 'user',
{ port: 22,
keys: ["id_rsa.pub"],
keys_only: true })
port = gateway.open('localhost', 3306, 3307)
client = Mysql2::Client.new(
host: "127.0.0.1",
username: 'root',
password: 'qwerty',
database: 'wp_blog',
port: port
)
results = client.query("show tables")
results.each do |row|
p row
end
client.close
gateway.shutdown!
- 2-3 - blog.bogojoker.com
- 7 - www.phptoruby.com
- 8 - www.ruby-doc.org
- 9 - www.ruby-forum.com
- 10 - stackoverflow.com
- 18 - stackoverflow.com
- 19 - stackoverflow.com
- 20 - stackoverflow.com
- 21 - www.ruby-doc.org
Ссылки по теме:
- hyperpolyglot.org - сравнение между php-perl-python-ruby