Recent Entries 10
- pattern critical 112d agoRuby: What does the comment "frozen_string_literal: true" do?This is the `rspec` binstub in my project directory. ``` #!/usr/bin/env ruby begin load File.expand_path("../spring", __FILE__) rescue LoadError end # frozen_string_literal: true # # This file was generated by Bundler. # # The application 'rspec' is installed as part of a gem, and # this file is here to facilitate running it. # require "pathname" ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../../Gemfile", Pathname.new(__FILE__).realpath) require "rubygems" require "bundler/setup" load Gem.bin_path("rspec-core", "rspec") ``` What is this intended to do? ``` # frozen_string_literal: true ```
- snippet critical 112d agoHow to map and remove nil values in RubyI have a `map` which either changes a value or sets it to nil. I then want to remove the nil entries from the list. The list doesn't need to be kept. This is what I currently have: `# A simple example function, which returns a value or nil def transform(n) rand > 0.5 ? n * 10 : nil } end items.map! { |x| transform(x) } # [1, 2, 3, 4, 5] => [10, nil, 30, 40, nil] items.reject! { |x| x.nil? } # [10, nil, 30, 40, nil] => [10, 30, 40] ` I'm aware I could just do a loop and conditionally collect in another array like this: `new_items = [] items.each do |x| x = transform(x) new_items.append(x) unless x.nil? end items = new_items ` But it doesn't seem that idiomatic. Is there a nice way to map a function over a list, removing/excluding the nils as you go?
- snippet critical 112d agoHow to break out from a ruby block?Here is `Bar#do_things`: ``` class Bar def do_things Foo.some_method(x) do |x| y = x.do_something return y_is_bad if y.bad? # how do i tell it to stop and return do_things? y.do_something_else end keep_doing_more_things end end ``` And here is `Foo#some_method`: ``` class Foo def self.some_method(targets, &block) targets.each do |target| begin r = yield(target) rescue failed << target end end end end ``` I thought about using raise, but I am trying to make it generic, so I don't want to put anything any specific in `Foo`.
- pattern critical 112d agoWhat is attr_accessor in Ruby?I am having a hard time understanding `attr_accessor` in Ruby. Can someone explain this to me?
- snippet major 112d agoHow can I test if a value lies within a Range?I'd like to be able to create a `Range` and then test if a variable is contained in that range. Something that looks like this: ``` fn main() { let a = 3..5; assert!(a.contains(4)); } ``` Right now, the only obvious thing I see is to use `Iterator::any`. This is ugly because it would take an O(1) operation and make it O(n): ``` fn main() { let mut a = 3..5; assert!(a.any(|v: i32| v == 4)); } ```
- debug minor 112d agoHow to solve "returns a value referencing data owned by the current function" error in Rust?I'm trying to code a binary tree that generates random expressions. I need random numbers and a set of functions. I receive a vector with the functions and the depth for the expression in the tree. In the operators vector, I also include a "ELEM" string, this is used to choose a random element from the vector and then change it for a float. It seems I still do not understand the exact use for borrows, moving and ownership, since it is a recursive function, it shows the error saying that value has been borrowed and cannot return a local variable. ``` use rand::Rng; struct Expression_Node { val: &'a str, left: Option>>, right: Option>>, } fn Create_Expression( operators: Vec, p: i32, ) -> std::option::Option>> { if p == 0 { let value = String::from(rand::thread_rng().gen::().to_string()); let value2: &str = value.as_ref(); //println!("{:?}", value); let new_node = Expression_Node { val: value2, left: None, right: None, }; return Some(Box::new(new_node)); } let value: &str = *rand::thread_rng().choose(&operators).unwrap(); println!("VAL: {:?}", value); if value == "ELEM" { let value = rand::thread_rng().gen::().to_string(); } let new_node = Expression_Node { val: value, left: Create_Expression(operators.clone(), p - 1), right: Create_Expression(operators.clone(), p - 1), }; return Some(Box::new(new_node)); } ``` The error: `error[E0515]: cannot return value referencing local variable `value` --> src/lib.rs:22:16 | 15 | let value2: &str = value.as_ref(); | ----- `value` is borrowed here ... 22 | return Some(Box::new(new_node)); | ^^^^^^^^^^^^^^^^^^^^^^^^ returns a value referencing data owned by the current function `
- debug major 112d agoOption types and early returns. return an Error when is_none()Using match (like in `bar`) seems to be a common approach.. ``` #[derive(Debug)] pub enum MyErrors { SomeError, } fn foo(x: Option) -> Result { if x.is_none() { return Err(MyErrors::SomeError); } // .. some long code where more options // are checked and matched // The ok here is just so the code is simple and compiles Ok(x.unwrap() * 2) } fn bar(x: Option) -> Result { match x { None => { return Err(MyErrors::SomeError)?; } Some(v) => { // .. some long code where more options // are checked and matched // The ok here is just so the code is simple and compiles Ok(x.unwrap() * 2) } } } fn main() { foo(Some(1)); bar(Some(2)); } ``` However, early returns (such as in `foo`) significantly reduce how nested the code looks like. If there are multiple times when an option has to be unwrapped or an error returned, code like bar gets very nested... What is the recommended practice for early returning an error in the case of empty options?
- pattern major 112d agoWhat is &'a in Rust LanguageI read here that A shared reference type is written `&type`, or `&'a type` when you need to specify an explicit lifetime. Understood `&` is for `shared reference` but did not understand what is the difference between `type` and `'a` in Rust language In another location I read this code: ``` #[derive(Debug)] struct Person { name: &'a str, age: u8 } fn main() { let name = "Peter"; let age = 27; let peter = Person { name, age }; // Pretty print println!("{:#?}", peter); } ``` What does `'a` in the `struct Person { }` means? and can I build the same `struct` using `struct Person { }` or `struct Person { }`? And what is the meaning of `name: &'a str`? And how can I re-code it, if want to avoid using the ``
- gotcha critical 112d agoWhy does Rust not have unions?I can think of many places where unions in C help are useful and they save memory. As Rust is a system programming language, why doesn't it support unions?
- gotcha moderate 112d agoWhy does passing a closure to function which accepts a function pointer not work?In the second edition of The Rust Programming Language (emphasis mine): Function pointers implement all three of the closure traits (`Fn`, `FnMut`, and `FnOnce`), so you can always pass a function pointer as an argument for a function that expects a closure. Itβs best to write functions using a generic type and one of the closure traits so your functions can accept either functions or closures. Passing a closure to a function which accepts a function pointer as an argument doesn't compile: ``` fn main() { let a = String::from("abc"); let x = || println!("{}", a); fn wrap(c: fn() -> ()) -> () { c() } wrap(x); } ``` `error[E0308]: mismatched types --> src/main.rs:10:10 | 10 | wrap(x); | ^ expected fn pointer, found closure | = note: expected type `fn()` found type `[closure@src/main.rs:4:13: 4:33 a:_]` ` Why does this not work?