Ruby gsub! change everything - ruby

in Ruby I have this situation
monurl = mon[0][1]['externallinks'][0]
nowlm = mon[0][1]['externallinks'][0]
with
mon[0][1]['externallinks'][0] = 'abc'
If I do
monurl.gsub!('a', 'z')
monurl is changed, but also mon[0][1]['externallinks'][0] and nowlm because of Ruby object management.
Is there a way to change only monurl and not mon[0][1]['externallinks'][0] and nowlm?
Thanks in advance.

monurl = monurl.gsub('a', 'z')
This changes monurl, but leaves nowlm and mon[0][1]['externallinks'][0] unchanged.

If you want monurl to manage its own copy of the string from the start, just let it refer to a copy of the string, and not to the original:
monurl = mon[0][1]['externallinks'][0].dup

Related

Ruby variable = variable

I'm taking a bootcamp course and I know line 4 (zip_code = zip_code) isn't necessarily needed but I've been told it's useful for a simple reason, but I'm not sure what that is. Anyone know why? Thanks so much.
class AdoptADog::Scraper
def self.scrape_dogs(zip_code)
base_url = "https://www.petsmartcharities.org/find-a-pet-results?city_or_zip="
zip_code = zip_code
last_url = "&species=dog&color_id&geo_range=50&pet_size_range_id&sex&age=&breed_id=69"
full_url = base_url + zip_code + last_url
html = open(full_url)
doc = Nokogiri::HTML(html)
doc.css(".pet-result").each do |dog|
name = dog.css(".pet-name").text
breed = dog.css(".pet-breed").text
sex = dog.css(".pet-sex").text
location = dog.css(".pet-addr-city-state").text
url = dog.css("a").attribute("href").value
AdoptADog::Dogs.new(name, breed, sex, location, url)
end
end
end
No, and the initial premise that it is useful is incorrect.
There is no functional reason for this, and I would argue against even the loose case one could make that it "increases readability".
This is pretty much bad practice in EVERY language.
The one and only possible reason for this would be to demonstrate variables to someone who is just starting to learn the core fundamentals of programming. Even that would be a bad example though, as it could be misunderstood to be good practice, when it most definitely is not, and there are FAR better ways to illustrate that without any risk of misconception.
maybe zip_code = zip_code.dup ?, you should not change the passed params in your function.
Could it be that you missed .dup or .clone ?
something = something.dup can be useful if you work with mutable object and don't wanna mess with original one.
Anyway, if you have been told that it is useful for some reason, why don't you just ask that person to elaborate?

can't remove optional() from string after updating to latest xcode?

after updating xcode I simply can't remove the optional() from my string?
retrievedUsername = KeychainWrapper.stringForKey("username")!
this prints out
optional("HK")
but I need it to be
HK
I've tried
if let username = KeychainWrapper.stringForKey("username"){
retrievedUsername = username
}
but no luck!
any ideas?
Your value is probably an optional containing an optional, so you'll have to unwrap it twice:
if let temp = KeychainWrapper.stringForKey("username"), let username = temp {
retrievedUsername = username
}
If this doesn't work, this is because it's not a double optional, and it means that your original string already contains the text "Optional(HK)" due to a prior error.
I found out the problem, it would save to the keychain with "optional" so when it retrieves the string it is "optional("HK")" that's why unwrapping it didn't work

More concise way of writing this array inclusion / default fallback code?

I find that I've been doing this a fair enough number of times in my Rails controllers that I'm interested in finding a better way of writing it out (if possible). Essentially, I'm validating the input to a few options, and falling back on a default value if the input doesn't match any of the options.
valid_options = %w(most_active most_recent most_popular)
#my_param = valid_options.include?(params[:my_param]) ? params[:my_param] : 'most_recent'
If you use a hash instead of an array, it would be faster and cleaner. And, since your default is "most_recent", having "most_recent" in valid_options is redundant. You better remove it.
filter_options =
Hash.new("most_recent")
.merge("most_popular" => "most_popular", "most_active" => "most_active")
#my_param = filter_options[params[:my_param]]
I too would go the Hash route.
This could be imaginable:
Hash[valid_options.zip valid_options].fetch(params[:my_param], "most_recent")
A bit farfetched.
valid_options = %w(most_active most_recent most_popular)
(valid_options & [params[:my_param]]).first || 'most_recent'
How is the below:
valid_options = %w(most_active most_recent most_popular)
valid_options.detect(proc{'default_value'}){|i| i == params[:my_param] }
Another one:
valid_options = %w(most_active most_recent most_popular)
valid_options.dup.delete(params[:my_param]) { "default" }

How to get part of string after some word with Ruby?

I have a string containing a path:
/var/www/project/data/path/to/file.mp3
I need to get the substring starting with '/data' and delete all before it. So, I need to get only /data/path/to/file.mp3.
What would be the fastest solution?
'/var/www/project/data/path/to/file.mp3'.match(/\/data.*/)[0]
=> "/data/path/to/file.mp3"
could be as easy as:
string = '/var/www/project/data/path/to/file.mp3'
path = string[/\/data.*/]
puts path
=> /data/path/to/file.mp3
Using regular expression is a good way. Though I am not familiar with ruby, I think ruby should have some function like "substring()"(maybe another name in ruby).
Here is a demo by using javascript:
var str = "/var/www/project/data/path/to/file.mp3";
var startIndex = str.indexOf("/data");
var result = str.substring(startIndex );
And the link on jsfiddle demo
I think the code in ruby is similar, you can check the documentation. Hope it's helpful.
Please try this:
"/var/www/project/data/path/to/file.mp3".scan(/\/var\/www(\/.+)*/)
It should return you all occurrences.

ruby one-liner for this possible?

Any chance the 2nd and 3rd lines can be combined in an one-liner and hopefully save one valuable?
def self.date_format
record = find_by_key('strftime')
record ? record.value : "%Y-%b-%d'
end
the above function in a Config model try to fetch a database record by a key, return a default if not found in database.
Even better if can be written in named scope. Thanks
As requested.
Nobody yet has mentioned try, which is perfect for this situation:
value = find_by_key('strftime').try(:value) || "%Y-%b-%d"
You could use:
(find_by_key('strftime').value rescue nil) || "%Y-%b-%d"
though using exceptions is not very efficient.
Does
value = find_by_key('strftime') || "%Y-%b-%d"
work for you?
Do you need to assign a "value" variable at all? If not...
def self.date_format
find_by_key('strftime') || "%Y-%b-%d"
end

Resources