今天我很惊讶地发现ruby自动找到作为块参数给出的数组的值.
例如:
foo = "foo"
bar = "bar"
p foo.chars.zip(bar.chars).map { |pair| pair }.first #=> ["f", "b"]
p foo.chars.zip(bar.chars).map { |a, b| "#{a},#{b}" }.first #=> "f,b"
p foo.chars.zip(bar.chars).map { |a, b,c| "#{a},#{b},#{c}" }.first #=> "f,b,"
Run Code Online (Sandbox Code Playgroud)
我原以为最后两个例子会出现某种错误.
在GitHub上,用户可以拥有固定存储库.
还有API 的Repositories部分描述了如何发出涉及repos的请求.您还可以获得有关用户所参与的组织的信息,如另一个答案(可以固定)中所述.
但是,我想访问用户的固定存储库.例如,给出以下配置文件:
我希望能够做到以下几点:
$ curl -s <some endpoint with some parameters> | <some pipeline with some filtering>
str
liffy_diffy
spiralify
micro-twitter
kit
xdoc
Run Code Online (Sandbox Code Playgroud)
所以我想知道:
我能够使用nokogiri gem来解析html.但是,似乎我应该api用简单的HTTP请求完成同样的事情:
$ ./get_user_pinned_repos mbigras
str
liffy_diffy
spiralify
micro-twitter
kit
xdoc
Run Code Online (Sandbox Code Playgroud)
码:
#!/usr/bin/env ruby
# get a user's pinned repos
require 'rubygems'
require 'nokogiri'
require 'open-uri'
if ARGV.length != 1
STDERR.puts "usage: get_user_pinned_repos <username>"
exit 1
end
username = ARGV.first
profile_url = "https://github.com/#{username}"
page = Nokogiri::HTML(open(profile_url)) …Run Code Online (Sandbox Code Playgroud) 给出以下代码:
def map(char, charmap)
unless map = charmap[[char]]
unless map = charmap[[char, c = input.getc]]
input.ungetc(c) if c
map = ''
end
end
map
end
Run Code Online (Sandbox Code Playgroud)
双方括号是做什么的?
谢谢
以下是文档中的一些片段Kernel:
在文件filename中加载并执行Ruby程序...
加载给定的名称......
我知道有差异require和load例如:
require上钉会rb延长,而load不会require将存储里面的ruby文件路径$LOADED_FEATURES又名$"而load不会require将$LOADED_FEATURES在"加载"文件之前搜索,而load不会我想知道"加载"这个词和"执行"这个词之间的区别.
文档使它看起来像是两个不同的东西.对我来说,"加载"意味着"嘿,我现在知道这个文件",而"执行"意味着"嘿,我现在知道这个文件,我也要运行所有的命令"
但我不认为这是对的.
例如,给定以下结构:
$ tree
.
??? bar.rb
??? baz.rb
??? foo.rb
0 directories, 3 files
Run Code Online (Sandbox Code Playgroud)
与foo.rb:
$LOAD_PATH << __dir__
require 'bar'
load 'baz.rb'
Run Code Online (Sandbox Code Playgroud)
bar.rb:
puts "Inside of bar..."
Run Code Online (Sandbox Code Playgroud)
baz.rb:
puts "Inside of baz..."
Run Code Online (Sandbox Code Playgroud)
当我跑步时,foo.rb我希望"在巴兹里面..."打印而不是"在酒吧里面..."因为load"加载并执行"而require只是"加载".但实际发生的事情似乎都是"执行":
$ ruby foo.rb
Inside of bar... …Run Code Online (Sandbox Code Playgroud) 使用 Ruby 的核心类/模块检查文件是否存在而不需要 shell 的所有方法有哪些?
还会理解为什么选择一种方法而不是另一种方法更有意义的原因。例如:使用Dir['**/*'].grep(/foo/)是我发现使用正则表达式匹配路径的最短方法。
然而,我认为Pathname.new('.').find.any? { |pn| pn.fnmatch? "*foo*" }这是一个不错的选择,因为Pathname是一个跨平台解决方案,通常看起来“正常工作”。
我错过了任何解决方案/课程/模块吗?另外,希望得到涉及速度/效率分析的答案。
require 'minitest/autorun'
require 'pathname'
class TestTouch < Minitest::Test
include FileUtils
attr_reader :foo
def setup
@foo = Pathname.new('foo')
foo.delete if foo.exist?
end
def teardown
foo.delete if foo.exist?
end
def test_touch
touch foo
cwd = Pathname.new('.')
assert cwd.find.to_a.map(&:to_s).grep(/foo/).any?
assert cwd.find.any? { |pn| pn.fnmatch? "*foo*" }
assert cwd.join('foo').exist?
assert Dir['**/*'].grep(/foo/)
assert Dir.glob('**/*').grep(/foo/)
assert !Dir.glob('foo').empty?
assert File.exist?('foo')
end
end
Run Code Online (Sandbox Code Playgroud) #each_with_object和#inject都可以用来构建哈希.
例如:
matrix = [['foo', 'bar'], ['cat', 'dog']]
some_hash = matrix.inject({}) do |memo, arr|
memo[arr[0]] = arr
memo # no implicit conversion of String into Integer (TypeError) if commented out
end
p some_hash # {"foo"=>["foo", "bar"], "cat"=>["cat", "dog"]}
another_hash = matrix.each_with_object({}) do |arr, memo|
memo[arr[0]] = arr
end
p another_hash # {"foo"=>["foo", "bar"], "cat"=>["cat", "dog"]}
Run Code Online (Sandbox Code Playgroud)
两者之间的关键差异之一是#each_with_object跟踪memo整个迭代,而#inject设置memo等于块在每次迭代时返回的值.
另一个区别是顺序或块参数.
有没有在这里传达意图?反转两种类似方法的块参数没有意义.
从手册页:
-a Turns on auto-split mode when used with -n or -p.
In auto-split mode, Ruby executes
$F = $_.split
at beginning of each loop.
Run Code Online (Sandbox Code Playgroud)
有些问题浮现在脑海中:
-a,而不使用-n或-p?$F?split?-a使用?从另一个参考页面:
$F The variable that receives the output from split when -a is specified.
This variable is set if the -a command-line option is specified
along with the -p or -n option.
Run Code Online (Sandbox Code Playgroud)
我还不确定是什么 …
当我使用默认值(如 0)初始化 Ruby 哈希并在哈希中创建一个新条目并递增时,它的行为符合预期:
irb(main):001:0> h1 = Hash.new(0)
=> {}
irb(main):002:0> h1[:foo] += 1
=> 1
irb(main):003:0> h1
=> {:foo=>1}
irb(main):004:0> h1[:foo]
=> 1
Run Code Online (Sandbox Code Playgroud)
注意如何h1 #=> {:foo=>1}和h1[:foo] #=> 1。这正是我所期待看到的。
除非我使用空数组的默认值,否则会发生以下情况:
irb(main):005:0> h2 = Hash.new([])
=> {}
irb(main):006:0> h2[:foo] << "cats"
=> ["cats"]
irb(main):007:0> h2
=> {}
irb(main):008:0> h2[:foo]
=> ["cats"]
Run Code Online (Sandbox Code Playgroud)
注意如何h2 #=> {}和h2[:foo] #=> ["cats"]。我不知道为什么会发生这种情况。
:foo?如果我使用一些块,那么就会发生预期的行为:
irb(main):001:0> h3 = Hash.new {|hash, key| hash[key] = [] } …Run Code Online (Sandbox Code Playgroud) 据我所知,优先级有所不同,如另一个答案所示:
p foo = false || true
# => true
p foo = false or true
# => false
Run Code Online (Sandbox Code Playgroud)
但似乎在or和之间存在更多不同的东西||.
例如:
p foo = 42 or raise "Something went wrong with foo"
# => 42
p foo = nil or raise "Something went wrong with foo"
# => Something went wrong with foo (RuntimeError)
p foo = 42 || raise "Something went wrong with foo"
# => syntax error, unexpected tOP_ASGN, expecting end-of-input
Run Code Online (Sandbox Code Playgroud)
我期待得到: …
ruby ×8
enumerable ×2
arrays ×1
block ×1
command-line ×1
concourse ×1
curl ×1
github ×1
github-api ×1
http ×1
operators ×1
string ×1