Notes posted to RubyRSS feed
Over the weekend I kept running into instances where I was writing code like this:
arr = ['hello', 'world'] if arr.length > 2 # do stuff else # do something else end
So I ended up extending the core and adding an instance method of more_than?
arr = ['hello', 'world'] puts "Hello" if arr.more_than? 1
Just adding an anchor to the regular expression seems simpler (and was faster in my benchmarks, not that that matters much):
'Abracadabra' =~ /^[A-Z]/
(or any regular expression you’d like)
'Abracadabra'[0..0] =~ /[A-Z]/ # => true
> o.methods NoMethodError: undefined method `methods’ for #<BasicObject:0x0000000267a0a0>
> def o.to_s > self > end
URI.join uses a delimiter – forward slash (/) – to decide if joined strings are a path or endpoint. In order to include strings as part of the path, they must end with a forward slash (/). Otherwise, they are assumed to be an endpoint and are overritten by your new “endpoint”.
Used this way, it (kind of) makes sense:
1.9.2p290 :021 > URI.join("http://localhost/test","main.json") => #<URI::HTTP:0x007fa68e81c270 URL:http://localhost/main.json> 1.9.2p290 :022 > URI.join("http://localhost/test/","main.json") => #<URI::HTTP:0x007fa68e80e0d0 URL:http://localhost/test/main.json>
It is especially confusing when you pass 3 strings and the 3rd (your endpoint) overwrites the 2nd (which you expected to be part of the path).
1.9.2p290 :023 > URI.join("http://localhost/", "test", "main.json") => #<URI::HTTP:0x007fa68cec0ba0 URL:http://localhost/main.json> 1.9.2p290 :024 > URI.join("http://localhost/", "test/", "main.json") => #<URI::HTTP:0x007fa68ce14c60 URL:http://localhost/test/main.json>
Now, consider that you are probably using a variable for the string value of ‘test’.
1.9.2p290 :025 > controller = 'test' 1.9.2p290 :026 > URI.join("http://localhost/", controller, "main.json") => #<URI::HTTP:0x007fa68cec0ba0 URL:http://localhost/main.json>
Your `controller` is simply ignored. Or rather, your endpoint(?) was overwritten.
I’m not sure what versions of ruby this affects. As you can see I am using 1.9.2p290.